PowerShell Handling Secrets and Credentials Working with Stored Credentials

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To store and retrieve encrypted credentials easily, use PowerShell's built-in XML serialization (Clixml):

$credential = Get-Credential

$credential | Export-CliXml -Path 'C:\My\Path\cred.xml'

To re-import:

$credential = Import-CliXml -Path 'C:\My\Path\cred.xml'

The important thing to remember is that by default this uses the Windows data protection API, and the key used to encrypt the password is specific to both the user and the machine that the code is running under.

As a result, the encrypted credential cannot be imported by a different user nor the same user on a different computer.

By encrypting several versions of the same credential with different running users and on different computers, you can have the same secret available to multiple users.

By putting the user and computer name in the file name, you can store all of the encrypted secrets in a way that allows for the same code to use them without hard coding anything:

Encrypter

# run as each user, and on each computer

$credential = Get-Credential

$credential | Export-CliXml -Path "C:\My\Secrets\myCred_${env:USERNAME}_${env:COMPUTERNAME}.xml"

The code that uses the stored credentials:

$credential = Import-CliXml -Path "C:\My\Secrets\myCred_${env:USERNAME}_${env:COMPUTERNAME}.xml"

The correct version of the file for the running user will be loaded automatically (or it will fail because the file doesn't exist).



Got any PowerShell Question?