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:
1 2 | $creds = Get-Credential $creds | Export-CliXml -Path '.\cred.xml' |
You could also condense into one line:
1 | 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:
1 | $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.
- 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.
- 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:
1 2 3 4 5 6 7 8 | $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.
By day, I’m a systems admin for a medium size company in the Pacific Northwest.
By night, I’m a blogger, gamer, and all around general nerd.
If you found one of my articles useful, please consider supporting this site!
Monero: 48PxwMvbwoB2M86sHespLBKcSL9cWxrnJDmga9XshSqRP1joykRNpKkDGUz4ohhxD1bMH92poMyZWBBqkPmQ2bHpLP4EDnz
Bitcoin: bc1qc0fyze8x9lxp42x5p3zpry6f0lsr6l5pgq4jkh
Ethereum: 0xc613cBc79Ea4a84AE5538ec3321E214363305121