On this page

PowerShell Credential Management: Secure Storage & Best Practices

Updated on June 26, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Effective credential management in PowerShell requires eliminating hard‑coded secrets and adopting a layered security approach. For interactive use, Get‑Credential provides a secure PSCredential object that stores passwords as SecureStrings. For local automation, DPAPI encryption via Export‑Clixml offers machine‑ and user‑bound protection. For enterprise environments, the SecretManagement module with vault backends (Azure Key Vault, SecretStore, HashiCorp Vault) provides centralized, auditable secret storage. Windows Credential Manager offers a built‑in alternative for local credential storage. For cloud‑native workloads, managed identities and certificate‑based authentication eliminate secret management overhead entirely. The enterprise standard is to store secrets in centralized vaults, retrieve them at runtime via SecretManagement or managed identities, enforce RBAC, rotate secrets automatically, and never persist credentials locally.


The PSCredential Object​

PowerShell provides a built‑in secure container for credentials: the [PSCredential] object. This object encapsulates a username (plain text) and a password stored as a SecureString. The SecureString type encrypts sensitive text in memory, reducing exposure to memory scraping attacks.

Creating Credentials Interactively​

The simplest way to obtain a PSCredential object is using the Get‑Credential cmdlet:


$cred = Get-Credential

This prompts the user securely and returns a [PSCredential] object. In Windows PowerShell 5.1 and earlier, a dialog box appears; in PowerShell 6.0 and later, the prompt is presented in the console for all platforms.

You can also pre‑populate the username:


$cred = Get-Credential -Credential "DOMAIN\User"

$cred = Get-Credential -UserName "DOMAIN\User" -Message "Enter your password"

When using the UserName parameter, you are also required to provide a Message value.

For advanced scenarios, the $Host.UI.PromptForCredential() method offers additional customization of the prompt caption and message:


$Credential = $Host.UI.PromptForCredential(

    "Need credentials",

    "Please enter your user name and password.",

    "",

    "NetBiosUserName"

)

This method is an alternative to Get-Credential that allows you to specify the caption, messages, and user name that appear in the prompt.

Using Credentials​

Once created, the credential object can be passed to any cmdlet or function that accepts a Credential parameter:


Invoke-Command -ComputerName Server01 -Credential $cred -ScriptBlock {

    Get-Service

}

This approach is safe for interactive use but unsuitable for automation—automated scripts cannot rely on user prompts.

Creating Credentials Non‑Interactively​

Automation requires creating credential objects without user interaction. This involves creating a SecureString from a plain‑text password (with the understanding that the plain text must come from a secure source):


$password = ConvertTo-SecureString "MyPlainTextPassword" -AsPlainText -Force

$cred = New-Object System.Management.Automation.PSCredential("username", $password)

Both the -AsPlainText and -Force parameters are required. PowerShell returns a warning because plain‑text passwords get recorded in various logs. This method should only be used when the password is retrieved from a secure vault, not when hard‑coded.

Limitations of Secure Strings​

While Secure Strings offer basic protection, they rely on the Windows Data Protection API (DPAPI) and can be decrypted under certain conditions. Any process running in the same user context—or an administrator on the same machine—can decrypt them:


$SecurePassword = ConvertTo-SecureString "P@ssw0rd123" -AsPlainText -Force

$DecryptedPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(

    [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)

)

The SecureStringToBSTR method converts the secure string to a plain‑text BSTR, and PtrToStringAuto retrieves the string. This demonstrates that Secure Strings are not a complete security boundary and should be supplemented with stronger mechanisms like secure vaults.


Storing Credentials with DPAPI​

PowerShell can encrypt secrets using the Data Protection API (DPAPI) , which ties encryption to the current user and machine context. Only the same user on the same machine can decrypt the data.

Exporting and Importing a Credential​


$cred = Get-Credential

$cred | Export-Clixml -Path "C:\Secure\service.cred"

$cred = Import-Clixml -Path "C:\Secure\service.cred"

The Export-Clixml cmdlet serializes the PSCredential object, and DPAPI automatically encrypts the password. The file is useless on any other machine or under any other user context. This is acceptable for single‑machine automation such as scheduled tasks.

Limitations of DPAPI​

DPAPI is not suitable for distributed systems, CI/CD pipelines, or environments where credentials must be shared across machines. Additionally, the encrypted file is bound to the user profile; if the user account is deleted or the machine is reimaged, the file becomes irrecoverable. Secure Strings relying on DPAPI can be trivially decrypted by any process running in the same user context in which they were encrypted.


Windows Credential Manager​

Windows includes a built‑in tool called Credential Manager that was first introduced with Windows 7. It stores credentials for websites, network locations, and applications in a secure location on your computer.

Credential Types​

Credential Manager can store three different types of credentials:

Using the CredentialManager Module​

The community CredentialManager module (available on PowerShell Gallery) provides simple commands for managing credentials:


Install-Module -Name CredentialManager

Import-Module -Name CredentialManager

Available commands:

Creating a Stored Credential​


New-StoredCredential -Credentials $(Get-Credential) -Target 'TestCreds' -Type Generic -Persist LocalMachine

Key parameters:

Retrieving a Stored Credential​


$cred = Get-StoredCredential -Target 'TestCreds'

This returns a PSCredential object that can be used directly.

Removing a Stored Credential​


Remove-StoredCredential -Target 'TestCreds'

Credential Manager is useful for local automation and interactive sessions, but it lacks centralized management, rotation, and audit features required for enterprise use. A common "gotcha" is forgetting to set the -Persist parameter to LOCAL_MACHINE, which means credentials are lost after reboot.


The SecretManagement Module​

For enterprise‑scale automation, Microsoft recommends the SecretManagement and SecretStore modules. The SecretManagement module is essentially an orchestrator for extension vaults that perform the actual secret storage and encryption. It provides a convenient way for a user to store and retrieve secrets.

Supported Vaults​

Installation and Configuration​


Install-Module -Name "Microsoft.PowerShell.SecretManagement"

Install-Module -Name "Microsoft.PowerShell.SecretStore"

Register-SecretVault -Name "SecretStore" -ModuleName "Microsoft.PowerShell.SecretStore" -DefaultVault

Set-SecretStoreConfiguration -Authentication None

The -Authentication None setting allows access to the secret store without requiring a password to unlock the vault—essential for unattended automation. For production, consider using a password or certificate to protect the vault itself. The SecretStore module stores secrets locally in files for the current user account context and uses .NET encryption APIs to encrypt the file content.

Storing and Retrieving Secrets​

Storing a secret


Set-Secret -Name "SqlPassword" -Secret "P@ssw0rd!"

For credential objects, you can store them directly:


Set-Secret -Name "MyCredential" -Secret (Get-Credential)

Retrieving a secret


$pwd = Get-Secret -Name "SqlPassword"

Get-Secret returns the secret as a SecureString by default.

Using Secrets as Credentials​


$cred = New-Object System.Management.Automation.PSCredential(

    "DOMAIN\ServiceAccount",

    (Get-Secret -Name "SqlPassword")

)

This approach is vault‑agnostic and supports enterprise‑grade auditing, rotation, and access control through the vault's native capabilities.

PnP PowerShell Integration​

PnP PowerShell integrates directly with SecretManagement:


Add-PnPStoredCredential -Name "https://yourtenant.sharepoint.com" -Username "[email protected]"

Connect-PnPOnline -Url "https://yourtenant.sharepoint.com" -Credentials "https://yourtenant.sharepoint.com"

You can also add a secret with a label that reflects your tenant URL and use it automatically:


Set-Secret -Name "https://yourtenant.sharepoint.com" -Secret (Get-Credential)

Connect-PnPOnline -Url "https://yourtenant.sharepoint.com"

PnP PowerShell will check the vault for a secret matching the URL. A URL like https://yourtenant.sharepoint.com/sites/demo will also match the secret; PnP PowerShell tries to match the most complete label first.

Removing a Secret​


Remove-Secret -Name "SqlPassword" -VaultName "SecretStore"

Managed Identities and Certificate Authentication​

Modern enterprise environments increasingly avoid passwords entirely. PowerShell supports passwordless authentication through managed identities and certificates.

Managed Identities in Azure​

When running in Azure—on virtual machines, Functions, Automation accounts, containers, or other Azure resources—the resource can authenticate automatically without storing any secrets. This is achieved through system‑assigned or user‑assigned managed identities.

Example using Azure PowerShell:


Connect-AzAccount -Identity

No credentials are stored, transmitted, or exposed.

Certificate‑Based Authentication​

Certificates can replace passwords for API authentication, service principals, internal services, and remote management. A certificate is installed in the local certificate store, and PowerShell uses its thumbprint to authenticate.

Example:


$cert = Get-ChildItem Cert:\CurrentUser\My\THUMBPRINT

Connect-AzAccount -ServicePrincipal -Tenant $tenantId -CertificateThumbprint $cert.Thumbprint -ApplicationId $appId

Beginning with Az.KeyVault 3.3.0, the module includes a SecretManagement extension that allows using SecretManagement cmdlets to interact with secrets stored in Azure Key Vault. Certificates support rotation, revocation, and strong cryptographic guarantees.


Common Mistakes to Avoid​

Expert‑level PowerShell developers avoid the following patterns entirely:

Hard‑Coding Passwords​


$password = "P@ssw0rd123"   # Never do this

Hard‑coded passwords expose credentials to anyone with access to the script file and may lead to credential leakage in version control systems or log files. Attack vectors include source code exposure, insider threats, and malware scanning for hardcoded secrets.

Plain‑Text Storage​


$username = "admin"

$password = Get-Content .\password.txt   # Insecure

Plain‑text files are easily readable and expose credentials to any process or user with file access.

Embedding Secrets in Scripts or Modules​

Scripts should never contain passwords, API keys, tokens, or connection strings with embedded secrets. Even if encrypted, the decryption key often accompanies the script, rendering the protection useless.

Leaking Secrets to Logs or Output​

Avoid writing credentials to console output, log files, or CI/CD build logs. This includes inadvertently passing credentials to Write-Host or Write-Output. Always use Set-Secret or other secure storage to hold secrets, and never echo them.


Enterprise Workflow for Credential Management​

A secure enterprise workflow typically follows these principles:

  1. Secrets are stored in a centralized vault
    Azure Key Vault, HashiCorp Vault, SecretStore, or hardware security modules (HSMs) are used as the authoritative source for all secrets.
  2. Access is controlled through RBAC
    Least‑privilege access is enforced, with role‑based permissions and audited access logs.
  3. Scripts retrieve secrets at runtime
    Using SecretManagement, managed identities, or certificate‑based authentication, scripts fetch credentials only when needed, never storing them persistently.
  4. Secrets are never stored locally
    No plain‑text files, no DPAPI (except for strictly local automation with no distribution), and no embedded credentials.
  5. Secrets are rotated regularly
    Automated rotation policies, vault‑driven expiration, and zero‑downtime credential updates ensure that credentials remain fresh and reduce the window of opportunity for attackers.

Summary​

Credential management is a foundational skill for secure PowerShell automation. At the expert level, you must:

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Code Signing

Next

Secure Strings and Secrets