CMJ Grubb

Storing an Encrypted Password for Powershell Scripting

Sometimes working in Powershell you need to run a script with stored credentials. The most common use case I've run into with this is sending Emails. It's kind of a pain because the encrypted file you create is dependent upon the user account on the computer - so no one else can use the encrypted file and you can't run it under your username on another computer. Thankfully, it's not too much of a pain in the neck to set up. The first step is to create the file with the encrypted password:

$SecureString = Read-Host -AsSecureString
$EncryptedPW = ConvertFrom-SecureString -SecureString $SecureString
Set-Content -Path "C:\Scripts\encryptedpw.txt" -Value $EncryptedPW

That first command will kick you to a new blank line, which is where you will enter the password you want to encrypt. Here is the code to use that password in the script:

$EncryptedPasswordFile = "C:\Scripts\encryptedpw.txt"
$username="user@contoso.com"
$password = Get-Content -Path $EncryptedPasswordFile | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PSCredential($username, $password)

That's it! Now whenever you need to use those credentials, you'll use the -credentials switch with the $credential argument.

Home