Managing Credentials (Part 1)

by Jan 4, 2017

Let’s assume you need to run a script every day that requires credentials. A safe way of storing credentials is to save them encrypted in a file. This code asks for credentials, then saves them in an XML file on your desktop:

$credential = Get-Credential -UserName train\user02 -Message 'Please provide credentials' 
$credential | Export-Clixml -Path "$home\desktop\myCredentials.xml"

The password is encrypted with your identity, so only you (and only on the machine where the credentials were saved) can access the credential.

Here is the code to read the saved credentials for later use:

$credential = Import-Clixml -Path "$home\desktop\myCredentials.xml"

# 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!