PoshCode Logo PowerShell Code Repository

Get-Credential 1.2 (modification of post by Joel Bennett view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/681"></script>download | new post

An improvement over the default Get-Credential cmdlet (doesn’t take much, eh?) offering, among other things, a -Console switch.

  1. ## Get-Credential
  2. ## An improvement over the default cmdlet which has no options ...
  3. ###################################################################################################
  4. ## History
  5. ## v 1.2 Refactor ShellIds key out to a variable, and wrap lines a bit
  6. ## v 1.1 Add -Console switch and set registry values accordingly (ouch)
  7. ## v 1.0 Add Title, Message, Domain, and UserName options to the Get-Credential cmdlet
  8. ###################################################################################################
  9. function Get-Credential{
  10. PARAM([String]$Title, [String]$Message, [String]$Domain, [String]$UserName, [switch]$Console)
  11.    $ShellIdKey = "HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds"
  12.    ## Carefully EA=SilentlyContinue because by default it's MISSING, not $False
  13.    $cp = (Get-ItemProperty $ShellIdKey ConsolePrompting -ea "SilentlyContinue")
  14.    ## Compare to $True, because by default it's $null ...
  15.    $cp = $cp.ConsolePrompting -eq $True
  16.  
  17.    if($Console -and !$cp) {
  18.       Set-ItemProperty $ShellIdKey ConsolePrompting $True
  19.    } elseif(!$Console -and $Console.IsPresent -and $cp) {
  20.       Set-ItemProperty $ShellIdKey ConsolePrompting $False
  21.    }
  22.  
  23.    ## Now call the Host.UI method ... if they don't have one, we'll die, yay.
  24.    $Host.UI.PromptForCredential($Title,$Message,$UserName,$Domain)
  25.  
  26.    ## BoyScouts: Leave everything better than you found it (I'm tempted to leave it = True)
  27.    Set-ItemProperty $ShellIdKey ConsolePrompting $cp
  28. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me