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.
- read-host will prompt you to enter the password
- The entered password will be encrypted with the provided key
- The secure password will be exported to the path of your choosing
- The password will be decrypted using the provided key and stored in the $password variable
- You will store the corresponding username in the $username variable
- 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