🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Secure Credentials

A secure credential is a username held together with a password that is stored in a protected form. It lets a script use an account without leaving a plain password in the script text.

Build a SecureString

ConvertTo-SecureString turns a plain password string into a protected SecureString. Print only the type name, never the password itself.

$password = ConvertTo-SecureString "TempPass123" -AsPlainText -Force
$password.GetType().Name

Build a PSCredential

A PSCredential pairs a username with a SecureString password. Print the username to confirm the account, and keep the password hidden.

$password = ConvertTo-SecureString "TempPass123" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("svc-backup", $password)
$credential.UserName

Pass a credential to a function

A function can take a PSCredential and use only its username for a message. The password stays hidden inside the object.

function Show-AccountName {
  param($Credential)
  $Credential.UserName
}
$password = ConvertTo-SecureString "TempPass123" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("svc-backup", $password)
Show-AccountName -Credential $credential

Example

$password = ConvertTo-SecureString "TempPass123" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential("svc-backup", $password)
$credential.UserName
$credential.GetType().Name
"Credential ready"

Key points

  • SecureString: a password held in a protected form that cannot be read as plain text.
  • PSCredential: an object that holds a username together with a SecureString password.
  • Use ConvertTo-SecureString with -AsPlainText and -Force to build a SecureString from a plain password string.
  • Use a PSCredential object to pass an account to a command that needs one.
  • A secure credential keeps the password out of the script output and out of plain text.

In this example, a plain password string is first turned into a SecureString. That SecureString is then paired with a username to build a PSCredential. The script prints only the username and the type name, plus a short ready message, and the password itself is never printed.

Note

Never print a SecureString or a password. Print only the username and the type name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a PSCredential object hold?