Two quick PowerShell code snippets. The first demonstrates how to take a plaintext password, encrypt it, and save it to a file. The second shows how to retrieve and decrypt the previously encrypted password.
To encrypt a plaintext password:
# password vault.
$vault = "C:\Scripts\pwd.txt"
# the password.
$password = "Passw0rd1#"
# save the password.
convertto-securestring -string $password -asplaintext -force | convertfrom-securestring | out-file $vault
To decrypt the saved password:
# password vault.
$vault = "C:\Scripts\pwd.txt"
# retrieve the password.
$securestring = convertto-securestring -string (get-content $vault)
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securestring)
$passwsord = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
The decryption code will only work if it is run on the same computer, and from the same user context under which the encryption code was executed. This limitation does not apply when the -key parameter is used with the convertto-securestring cmdlet.