password prompt

Save a Password Securely to Use with PowerShell

Q: How can I securely save a password used in a PowerShell credential?

A: In PowerShell, a credential object can be created that specifies the username and password. However, the password would typically be stored in plain text; for example:

$securepassword = ConvertTo-SecureString -string "<your password>" -AsPlainText -Force 

$cred = new-object System.Management.Automation.PSCredential ("<your logon>", $securepassword)

There are several options. The TechNet article "Manipulate credentials in the Windows 8/2012 PasswordVault using Powershell" discusses a third-party module that stores credentials in the Windows password vault.

Another option is to create a secure, encrypted version of the password, using

$encryptedPassword = ConvertFrom-SecureString (ConvertTo-SecureString -AsPlainText -Force "Password123")

Use the output of this command in your script. Obviously, if someone noted the entire value, they would get your password. However, this information is fairly lengthy to quickly write down:

$passwordAsSecureString = ConvertTo-SecureString "<the huge value from previous command>"

Another option if you don't want the password in the encrypted form visible in the script is that you can save the entire credential to a file in secure form that's only be accessible as your user account on the specific machine; for example:

$credpath = c:\temp\MyCredential.xml
New-Object System.Management.Automation.PSCredential("<account>", (ConvertTo-SecureString -AsPlainText -Force "Password123")) | Export-CliXml $credpath

To then use the credential from the file in my script, I would use

$cred = import-clixml -path $credpath

Note that the Export-CliXml and the PowerShell module specified both use the same crypto API (DPAPI) under the hood and therefore have the same strengths and weaknesses. The difference is that Export-CliXml saves to a file, whereas the PowerShell module saves to the Windows registry in an encrypted form.

If you're using this method with Azure credentials, it will only work with Azure Active Directory accounts and not Microsoft IDs (Live IDs).

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.