Converting SecureString to Clear Text

by Nov 27, 2018

Secure string content cannot be easily viewed:

$password = Read-Host -Prompt 'Your password' -AsSecureString
 
PS C:\> $password
System.Security.SecureString 
 

However, if you are the one who asked for the secure string in the first place, you can easily convert it back into plain text with this clever trick:

$txt = [PSCredential]::new("X", $Password).GetNetworkCredential().Password
$txt

Essentially, the SecureString is used to create a PSCredential object, and a PSCredential object contains the method GetNetworkCredential() which automatically converts the encrypted password into clear text.

This way, you could use the masked input box provided by Read-Host –AsSecureString to ask for sensitive information even if you need this information as plain text string:

function Read-HostSecret([Parameter(Mandatory)]$Prompt)
{
  $password = Read-Host -Prompt $Prompt -AsSecureString
  [PSCredential]::new("X", $Password).GetNetworkCredential().Password
}
 
PS C:\> Read-HostSecret -Prompt 'Your secret second first name'
Your secret second first name: ********
Valentin

PS C:\>
 

Twitter This Tip! ReTweet this Tip!