Credentials

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.

[code lang=powershell]
Get-Credential -Message "Creds Please"
[/code]

Credential Window

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

[code lang=powershell]
Get-Credential -Username LebowskiTheDude
[/code]

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.

[code lang=powershell]
$Credentials = Get-Credential
[/code]

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.

[code lang=powershell]
Get-Credential -Username LebowskiTheDude | Export-clixml -path c:credentials.xml $Credentials = Import-clixml -path c:credentials.xml
[/code]

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.

[code lang=text]
C:Usersngetchell> 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
[/code]

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.

[code lang=powershell]
get-command -ParameterType PSCredential
[/code]

One thought on “Credentials

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.