This article was first published in December 2019 and completely revised in November 2026.

Passwords in scripts. We all know we should not put them in plain text, yet a test script with a real password has a way of ending up in production, in Git or in a screenshot. This article walks through the ways to handle passwords in PowerShell, starting with the simplest and ending with the ones I would actually use today. Along the way I point out which methods only look safe.

Which method when?

SituationUseRemark
Interactive, on your own machine (Windows, macOS or Linux)SecretManagement with SecretStoreThe default choice. Encrypted per user, works everywhere.
Script on a schedule that talks to AzureManaged identityNo secret to store at all.
Windows service with an Active Directory accountGroup managed service account (gMSA)Windows rotates the password for you.
Team or production, many scripts, audit trail neededAzure Key Vault or HashiCorp VaultAccess policies, logging and rotation. Reachable through SecretManagement or the API.
Just once, to try somethingRead-Host -AsSecureString or Get-CredentialNever put the password in the script.

Everything below is explained in this order: the building blocks (SecureString and PSCredential), the older do-it-yourself methods and why I stopped using them, and then the recommended tools.

SecureString and PSCredential

The simplest way to hold a password is a string. That is plain text, so most cmdlets that need a password do not accept it. They want a SecureString or a PSCredential. You can create a SecureString from plain text, but then the plain text has been in your script, your history and your memory. Prefer to ask for it:

$password       = "PlainTextPassword"   # only for testing: this is plain text in your script
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force

# better: ask for it
$securePassword = Read-Host -Prompt "Password" -AsSecureString

-AsPlainText -Force is deliberately awkward: PowerShell wants you to confirm that you know this string is not protected.

The PowerShell ISE input window that appears for Read-Host -AsSecureString, with the typed password shown as dots

Converting back to plain text is sometimes needed, for example for a web API that wants a string. In PowerShell 7 that is one command, in every version you can go through a PSCredential:

# PowerShell 7 and later
$plain = $securePassword | ConvertFrom-SecureString -AsPlainText

# works in every version
$plain = [pscredential]::new("user", $securePassword).GetNetworkCredential().Password

The older approach with SecureStringToBSTR still works, but make sure you free the memory afterwards and use PtrToStringBSTR (not PtrToStringAuto):

$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword)
try   { $plain = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr) }
finally { [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr) }

Get-Credential

Get-Credential returns a PSCredential: an object with a user name and a password as a SecureString. It shows a pop-up, which is clumsy in an automatic script. Without the pop-up you create the same object yourself:

$credential = Get-Credential -Message "Add credentials" -UserName "lab\administrator"

# without a pop-up
$credential = [pscredential]::new("lab\administrator", $securePassword)

The Windows PowerShell credential request pop-up with a user name and a masked password

The $credential variable in PowerShell showing the user name and a System.Security.SecureString as password

The “encrypted string”: convenient, but not what it seems

The old trick is to turn the SecureString into a string with ConvertFrom-SecureString and save that in a file. I called this a hash in the original version of this article. That was wrong: a hash cannot be reversed, and this can. It is an encrypted string.

# save
$securePassword | ConvertFrom-SecureString | Set-Content -Path "C:\powershell\Password.enc"

# read it back
$securePassword = Get-Content -Path "C:\powershell\Password.enc" | ConvertTo-SecureString

A long hexadecimal string in a Windows PowerShell window: the encrypted form of a password

On Windows this uses the Data Protection API (DPAPI). Only the same user on the same machine can decrypt it. That is a reasonable protection, as long as you keep that limitation in mind: when you change the password you have to create the file again.

On macOS and Linux it is not encrypted at all. Without a key, PowerShell 7 simply writes the password as hexadecimal text. I tested this on macOS: you can read it with three lines.

# on macOS or Linux: the "encrypted" string is just the password in hexadecimal UTF-16
$text  = "Voorbeeld123!" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
$bytes = for ($i = 0; $i -lt $text.Length; $i += 2) { [Convert]::ToByte($text.Substring($i, 2), 16) }
[System.Text.Encoding]::Unicode.GetString($bytes)   # Voorbeeld123!

Microsoft also advises against using SecureString in new code (DE0001), because it is only truly protected on Windows.

An AES key as an alternative

To make the encrypted string usable on another machine or by another user, you can encrypt with your own 256-bit AES key. That works on every platform:

# create a random 256-bit key
$key = [byte[]]::new(32)
[System.Security.Cryptography.RandomNumberGenerator]::Fill($key)       # PowerShell 7 / .NET Core 3.0+
# [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($key)   # Windows PowerShell 5.1

# encrypt and decrypt with the key
$encrypted      = ConvertFrom-SecureString -SecureString $securePassword -Key $key
$securePassword = ConvertTo-SecureString -String $encrypted -Key $key

The key is the password. A key file next to the encrypted file protects nothing, and I used to suggest protecting the key with DPAPI, which is circular: then you are back to a personal, per-machine secret. If you use this method, keep the key somewhere else, with restricted rights. For anything serious, use the tools below.

Recommended: SecretManagement and SecretStore

Microsoft.PowerShell.SecretManagement is the standard way to handle secrets in PowerShell. It gives you the same cmdlets (Get-Secret, Set-Secret) for different places where secrets live, called vaults. SecretStore is a vault that stores secrets encrypted on your own machine, on Windows, macOS and Linux.

Install-Module Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore -Scope CurrentUser
Register-SecretVault -Name LocalStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault

The first time you store a secret, SecretStore asks you for a password for the store. After that:

# store a credential and a plain secret
Set-Secret -Name LabAdmin -Secret (Get-Credential -UserName "lab\administrator" -Message "Lab admin")
Set-Secret -Name ApiKey   -Secret "abc123-example"

# read them back
$credential = Get-Secret -Name LabAdmin                  # PSCredential
$apiKey     = Get-Secret -Name ApiKey -AsPlainText       # plain string

# list and remove
Get-SecretInfo
Remove-Secret -Name ApiKey -Vault LocalStore

Get-Secret returns a PSCredential when you stored one, so you can pass it straight to any cmdlet that takes -Credential. I tested all of the above on macOS with PowerShell 7.

Unattended scripts

By default SecretStore asks for its password, which is no use for a scheduled job. You can switch the password off, but be aware of what that means: then anyone who can run code as your user can read the store.

# the first configuration needs a start password, even when you switch the password off
$start = Read-Host -Prompt "Start password for the store" -AsSecureString
Set-SecretStoreConfiguration -Authentication None -Interaction None -Password $start -Confirm:$false

For unattended jobs I would rather not store anything on the machine at all: use a managed identity or gMSA where you can, or a vault that gives the script its own limited access.

Other vaults through SecretManagement

The same cmdlets work with other vaults, through extension modules. The extension modules are separate projects, so check their documentation for the current parameters. I did not run the examples in this section here.

KeePass

KeePass is a free password manager with one database file. The SecretManagement.KeePass extension lets PowerShell read from it. It replaces the home-made KeePass functions I used in the first version of this article.

Install-Module SecretManagement.KeePass -Scope CurrentUser
Register-SecretVault -Name KeePass -ModuleName SecretManagement.KeePass `
    -VaultParameters @{ Path = "C:\powershell\TestDatabase.kdbx"; UseMasterPassword = $true }

Get-Secret -Name "Powershell" -Vault KeePass   # asks for the master password

Azure Key Vault

Install-Module Az.KeyVault -Scope CurrentUser
Register-SecretVault -Name AzureKV -ModuleName Az.KeyVault `
    -VaultParameters @{ AZKVaultName = "kv-example"; SubscriptionId = "<subscription-id>" }

Get-Secret -Name "vsphere-api" -Vault AzureKV -AsPlainText

Windows Credential Manager

Every Windows machine has a Credential Manager, and the CredentialManager module can read it from PowerShell. It is Windows only and the module has seen little development in recent years, so I would use SecretStore for new work. If you do use it on a server without internet access, run Save-Module CredentialManager -Path C:\temp on a machine that has internet and copy the folder to the server.

Install-Module -Name CredentialManager -Scope CurrentUser

# create a credential
New-StoredCredential -Target Administrator -UserName Administrator -Password "ZeerGeheimPassword!"

# read it as a PSCredential
$credential = Get-StoredCredential -Target Administrator

# read the password as plain text
$plaintext = (Get-StoredCredential -Target Administrator -AsCredentialObject).Password

# remove it
Remove-StoredCredential -Target Administrator

New-StoredCredential in PowerShell and the resulting stored credential for the target Administrator

Get-StoredCredential for the target Administrator returns the user name and a SecureString

Reading the password as plain text and removing the credential works as in the code above. The credential manager lists every credential for the current user, so you will see more than the one you created.

HashiCorp Vault

HashiCorp Vault is the tool I would choose for a team: access policies, an audit log and the option to let secrets expire. There is a community extension for SecretManagement, but because Vault has a clean REST API, calling it directly is easy too. How to set Vault up is in my earlier articles HashiCorp Vault on Windows with PowerShell and HashiCorp Vault in a Podman container on macOS.

For scripts, log in with an AppRole instead of a personal token. The role id and secret id come from the environment of the job, not from the script:

$vault   = "https://vault.example.com:8200"

# log in with AppRole and get a token
$login   = @{ role_id = $env:VAULT_ROLE_ID; secret_id = $env:VAULT_SECRET_ID } | ConvertTo-Json
$auth    = Invoke-RestMethod -Method Post -Uri "$vault/v1/auth/approle/login" -Body $login -ContentType "application/json"
$headers = @{ "X-Vault-Token" = $auth.auth.client_token }

Build the JSON with ConvertTo-Json, not by pasting strings together: a password with a quotation mark would otherwise break the request (and that is how I used to do it).

# write a secret to a KV version 2 secrets engine
$body = @{ data = @{ username = "Administrator"; password = $plainPassword; server = "srv01" } } | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri "$vault/v1/kv/data/vsphere_api/prd" -Headers $headers -Body $body -ContentType "application/json"
# read it back and make a PSCredential
$secret     = Invoke-RestMethod -Method Get -Uri "$vault/v1/kv/data/vsphere_api/prd" -Headers $headers
$username   = $secret.data.data.username
$password   = $secret.data.data.password | ConvertTo-SecureString -AsPlainText -Force
$credential = [pscredential]::new($username, $password)

I have not run the Vault examples here, but they follow the documented API for AppRole and the KV version 2 engine.

Do not leak the password somewhere else

  • Command line: never pass a password as an argument. Other users can see it in the process list, and it ends up in the history.
  • History and transcripts: a typed -AsPlainText -Force string is saved in the PSReadLine history, and in transcripts and script block logs. Check where yours is with the command below, and use Read-Host -AsSecureString or SecretManagement instead.
  • Files: restrict the rights of every file that contains a key or an encrypted password, and keep it out of Git (.gitignore, and a scanner such as gitleaks in your pipeline).
  • Least privilege and rotation: give every script its own account with only the rights it needs, and change the password regularly.
(Get-PSReadLineOption).HistorySavePath

What happened to my own modules?

The first version of this article used my own PowerShell modules, PSPassword and PSVault. They are old and no longer maintained, and SecretManagement does the same job better, so I no longer recommend them.

Summary

  • Never put a plain text password in a script, even a test script.
  • The output of ConvertFrom-SecureString is an encrypted string, not a hash, and on macOS and Linux it is not encrypted without a key.
  • Use SecretManagement with SecretStore on your own machine, and a managed identity, gMSA or a vault such as Azure Key Vault or HashiCorp Vault for scripts that run without you.