You may want to investigate the Protect-CMSMessage cmdlet, which allows you to encrypt/decrypt data using public key cryptography so that only users with the correct certificate would be able to decrypt the password.
If that seems like overkill, another, easier but possibly less secure, option is to export the credentials to XML and read them back when required.
To create the file, do this:
- Log on as the user the script will be running as
- Execute this command:
Get-Credential | Export-CliXml <path>cred.xml
- When prompted enter the username/password to be used in the script
The resulting XML file will have the username and password securely stored and can be read back like this:
$cred = Import-CliXml <path>cred.xml
You can then pass $cred
to any cmdlet that has a -Credential
parameter.
The password is encrypted in such a way that it can only be opened by the same user on the same computer, so if someone else opens it they won't be able to access the details. Obviously, if they can log on as the user who encrypted it (or convince that user to run a 'bad' script), then they will have access to the details, but otherwise this is pretty secure.
A third option is to use the built-in Credential Manager in Windows. This needs some complicated .NET interop for older systems, but luckily some nice person has already done the hard work for you:
PowerShell Credentials Manager
This is a bit easier in Windows 10:
PasswordVault Class
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…