Powershell – Encrypt and Decrypt Credentials

When getting into automation and script writing with Powershell you will find that you are needing to enter credentials into your scripts on a frequent basis. To get around having to place your plaintext password into your scripts you are able to encrypt this data into an XML and then retrieve the data as required.


You can generate the AES key by following this post.

The encryption only needs to be performed once, and then you can place the decryption code at the beginning of your scripts.

Code description


  1. read-host will prompt you to enter the password
  2. The entered password will be encrypted with the provided key
  3. The secure password will be exported to the path of your choosing


  1. The password will be decrypted using the provided key and stored in the $password variable
  2. You will store the corresponding username in the $username variable
  3. The credentials will be stored as a PSCredential object and be put in the $cred variable for use within your script



$Key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)
read-host -assecurestring | convertfrom-securestring -key $key | out-file 'C:\temp\Encrypted_PW.xml' 


$Key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)
$password = cat 'C:\temp\Encrypted_PW.xml' | convertto-securestring -key $key

$username = "matthben"
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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