PowerShell scripts often need credentials to access services, but passwords should never be embedded in source code, command-line arguments, or logs. Choose an authentication method that fits the workload, and keep secret storage separate from the script.
Prompt for an interactive credential
$Credential = Get-Credential
# Pass $Credential to a cmdlet that supports -Credential
Get-Credential prompts the signed-in user and returns a PSCredential object. This works for interactive tasks; it is not a solution for unattended jobs that cannot display a prompt. Prefer integrated authentication, a managed identity, or another approved workload identity when the service supports it.
Use encrypted CLIXML only in its supported scope
$Credential = Get-Credential
$Path = Join-Path $env:USERPROFILE "service-credential.xml"
$Credential | Export-Clixml -Path $Path
# Later, under the same Windows user account on the same computer:
$Credential = Import-Clixml -Path $Path
On Windows, Export-Clixml protects credential objects with DPAPI. The saved credential can be decrypted only by the same user on the same computer. Protect the file with appropriate filesystem permissions; do not treat it as a portable secret backup. On non-Windows platforms, credential passwords exported to CLIXML are not encrypted in the same way, so do not use this pattern there for password protection.
Avoid plaintext password conversions
Do not put a real password in code like ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force. The literal remains readable in the script, its history, backups, and source-control records. A SecureString is not a general-purpose vault and does not make a hard-coded secret safe.
Use an approved secret vault for automation
For unattended automation, prefer a managed identity or a platform-supported secret store such as Azure Key Vault. PowerShell’s SecretManagement module provides a common interface to registered vault extensions; the extension vault performs the actual storage and retrieval. Use only a vault extension approved by your organization and from a trusted source. Grant the job only the access it needs and avoid writing secret values to output, transcripts, or logs.
Credential-handling checklist
- Do not hard-code passwords, tokens, or private keys.
- Use the least-privileged identity suitable for the task.
- Keep local credential files out of shared folders and source control.
- Limit who and what can read a secret, and rotate it according to policy.
- Review error handling and logs to ensure they never print credentials.
See Microsoft’s documentation for Export-Clixml credential behavior and the SecretManagement model and its extension vaults. Select storage based on your platform, threat model, and operational requirements.