Storing Credentials for PowerShell

When working locally on PowerShell scripts I am quite frequently re-running them; and rather then let my self hard-code my credentials into my script which would be the easy (and less secure) thing to do, I did some digging to figure out now to securely store them.

$credpath = "v:\crypt\token.xml"
Get-Credential |  Export-CliXml $credpath

This will prompt for an interactive dialog box where you enter your password, and it is then written as a secure string to an xml file to the path identified.

Now this can easily be used in a number of scripts on the local machine without the need to enter credentials interactively which is helpful for repeated runs and automation scenarios as well where there might not always be an interactive UI.

$credpath = "v:\crypt\token.xml"
$cred = import-clixml -path $credpath

This file can only be used by the user and the machine where it was created; you should keep the file somewhere secure like an encrypted USB Drive or VeraCrypt partition.

If you happen to use two user accounts or two machines you can test this by running this script that will display your password on the user account and machine where the credential was created, and fail on an account or machine where it was not.  Note don’t do this in front of an audience.

$credpath = "v:\crypt\token.xml"

$cred = import-clixml -path $credpath
write-host $cred.GetNetworkCredential().password

I have found this a very helpful way to cut down my runtime when building out powershell scripts as well as prevent accidently committing or sharing my credentials with a co-worker.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s