Credentials

Have you ever tried running a script only to find that your user account doesn’t have the proper rights? You could start up another PowerShell session using the ‘Run as Different User’ option but wouldn’t you rather a PowerShell way? There is. PowerShell offers the PSCredential object type that allows you to store and retrieve credentials. This comes built into the Microsoft.PowerShell.Security module.

Running Get-Credential prompts the user for a username and password.

 Get-Credential -Message "Creds Please"

To fill the username prompt in simply use the -Username argument.

Get-Credential -Username LebowskiTheDude

PSCredential objects can be stored in variables just like any other object in PowerShell. Here the prompt comes up and when you click ‘OK’ the output of Get-Credential is stored in the $Credentials variable.

$Credentials = Get-Credential

PSCredentials can also be stored to disk with high fidelity. Saving a PSCredential object in a Command Line XML file allows for the importing at a later time.

Get-Credential -Username LebowskiTheDude | 
    Export-clixml -path c:\credentials.xml 
    
$Credentials = Import-clixml -path c:\credentials.xml

You’ll notice when you open up the resulting .xml file you can see the username but the password is encrypted. Only you can import the file. When another use tries to import it they get the following.

PS:\> Import-Clixml C:\credentials.xml 
Import-Clixml : Key not valid for use in specified state. At line:1 char:1 + Import-Clixml C:\credentials.xml + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Import-Clixml], CryptographicException + FullyQualifiedErrorId : System.Security.Cryptography.CryptographicException,Microsoft.PowerShell.Commands.Import ClixmlCommand

Get-Credential and the PSCredential object are extremely useful. To find out all of the commands that except the PSCredential object you can check with Get-Command.

get-command -ParameterType PSCredential