Save Credentials to a File

We’ve all been guilty of it once in awhile. You know what I’m talking about.

Saving plain text credentials into a script. It’s great for testing in certain situations. I’ve even been guilty of saving a script and keeping it for awhile on my laptop with the credentials in plain text. It’s just to convenient and easy. (Any one who says they’ve never done the same is a dirty, dirty liar.. but I digress).

But, in all honesty, it’s a terrible practice to get into, and a massive security issue that can easily be avoided. ( At least on a Windows machine. More on that later.)

The gist of it looks like so:

$creds = Get-Credential
$creds | Export-CliXml -Path '.\cred.xml'

You could also condense into one line:

Get-Credential | Export-CliXml -Path '.\cred.xml'

Either way, you will be prompted to input the username and password:

This will export an XML file to the path specified. It will look similar to this:

See that “Password” tag? That’s your encrypted password.

To use your stored credentials in a script, you’ll need to do like so:

$creds = Import-CliXml -Path '.\cred.xml'

From there you can use $creds in any place you need within the script.

Now for the caveats with using this method.

  1. You can only use the stored password on the same machine and logged in as the same user it was generated with. So no, you cannot share this file with someone and expect it to work for them. You will need to generate a new XML file.
  2. DO NOT USE THIS METHOD ON LINUX OR A MAC. It doesn’t encrypt the password. Microsoft even warns against this in Example 4 of their documentation here.

Now that that’s out of the way.

Storing even encrypted passwords on a machine in still a security risk, but this is a much better alternative than plain text passwords sitting in a script.

Added bonus:

Need to share a script, and want to give the person using it an easy way to add the credentials? You could add a bit of code to your script to check in the $env:userprofile for the xml file and if it doesn’t exist have the script prompt the user to create it automatically like so:

$cred_search = (ls $env:userprofile).name
if ($cred_search -notcontains "creds.xml"){
    $creds = Get-Credential
    $creds | Export-CliXml -Path $env:userprofile\creds.xml
if ($cred_search -contains "creds.xml"){
    Write-Host "Yay for Encrypted Creds"

You could even use $env:username, $env:hostname, and script name to name the XML file if you have multiple scripts that need credentials saved.

Leave a Reply

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