Managing Credentials (Part 4)

by Jan 9, 2017

In the previous script we showed how you can save a credential object in encrypted form to disk. A similar approach just saves the secret password as encrypted text. This creates the encrypted password file:

# read in the password, and save it encrypted
$text = Read-Host -AsSecureString -Prompt 'Enter Password'
$text | Export-Clixml -Path "$home\desktop\mypassword.xml"

It can only be read back from the person that saved it, and only on the same machine. A second script could take the password and use it to log in to another system without user interaction:

# read in the secret and encrypted password from file
$password = Import-Clixml -Path "$home\desktop\mypassword.xml"

# add the username and create a credential object
$username = 'yourCompany\yourUserName'
$credential = New-Object -TypeName PSCredential($username, $password)

The credential object can then be used with any cmdlet that takes the -Credential parameter.

# use the credential with any cmdlet that exposes the –Credential parameter
# to log in to remote systems
Get-WmiObject -Class Win32_LogicalDisk -ComputerName SomeServer -Credential $credential

Twitter This Tip! ReTweet this Tip!