$Variable = Read-Host "Enter thing" -AsSecureString
Will prompt you for input and save it as a secure string to variable. How do I decrypt a secure string variable?
PS C:\Users\Todd> $Variable
System.Security.SecureString
$Variable = Read-Host "Enter thing" -AsSecureString
Will prompt you for input and save it as a secure string to variable. How do I decrypt a secure string variable?
PS C:\Users\Todd> $Variable
System.Security.SecureString
A security warning first:
Converting a secure string to a regular [string]
instance defeats the very purpose of using [securestring]
(System.Security.SecureString
) to begin with: you'll end up with a plain-text representation of your sensitive data in your process' memory whose lifetime you cannot control.
Also, note that secure strings are generally not recommended for use in new code anymore: they offer only limited protection on Windows, and virtually none on Unix-like platforms, where they aren't even encrypted.
PowerShell v7+ now offers ConvertFrom-SecureString -AsPlainText
to convert a secure string to its - unsecured - plain-text representation:
# PowerShell 7.0 or higher.
$password = Read-Host "Enter password" -AsSecureString
$plainTextPassword = ConvertFrom-SecureString -AsPlainText $password
In PowerShell v6- (including Windows PowerShell), you can use the following:
$password = Read-Host "Enter password" -AsSecureString
$plainTextPassword = [Net.NetworkCredential]::new('', $password).Password
$password = Read-Host "Enter password" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
$password = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($password)
echo $password
pause
To convert Read-Host
SecureString
s to normal strings, you use
$NewVaraible = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReadVariable)
$NewNewVariable = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($NewVariable)
Or you could just update the existing variable:
$ReadVaraible = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($ReadVariable)
$ReadVariable = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ReadVariable)