Problem
Your script performs an operation that requires credentials, but you don’t want it to require user interaction when it runs.
Solution
To securely store the credential’s password to disk so that your script can load it automatically, use the ConvertFromSecureString and ConvertToSecureString cmdlets.
Save the credential’s password to disk
The first step for storing a password on disk is usually a manual one. Given a credential that you’ve stored in the $credential variable, you can safely export its password to password.txt using the following command:
PS >$credential.Password | ConvertFromSecureString | SetContent c:\temp\password.txt
Recreate the credential from the password stored on disk
In the script that you want to run automatically, add the following commands:
$password = GetContent c:\temp\password.txt | ConvertToSecureString
$credential = NewObject System.Management.Automation.PsCredential `
"CachedUser",$password
These commands create a new credential object (for the CachedUser user) and store that object in the $credential variable.
Discussion
When reading the solution, you might at first be wary of storing a password on disk. While it is natural (and prudent) to be cautious of littering your hard drive with sensitive information, the ConvertFromSecureString cmdlet encrypts this data using Windows’ standard Data Protection API. This ensures that only your user account can properly decrypt its contents.
While keeping a password secure is an important security feature, you may sometimes want to store a password (or other sensitive information) on disk so that other accounts have access to it anyway. This is often the case with scripts run by service accounts or scripts designed to be transferred between computers. The ConvertFromSecureString and ConvertToSecureString cmdlets support this by letting you to specify an encryption key.
When used with a hardcoded encryption key, this technique no longer acts as a security measure. If a user can access to the content of your automated script, they have access to the encryption key. If the user
has access to the encryption key, they have access to the data you were trying to protect.
Although the solution stores the password in a specific named file, it is more common to store the file in a more generic location—such as the directory that contains the script, or the directory that contains your profile.
To load password.txt from the same location as your profile, use the following command:
$passwordFile = JoinPath (SplitPath $profile) password.txt $password = GetContent $passwordFile | ConvertToSecureString
For more information about the ConvertToSecureString and ConvertFromSecureString cmdlets, type GetHelp ConvertToSecureString or GetHelp ConvertFromSecureString.