Ying Li at myITforum.com

PowerShell & System Center

How to enter password as secure string

In PowerShell script or interactive session, sometimes we will need to ask and store user password information. See below recorded PowerShell session:

PS C:\PS> $name = read-host "Please Enter Your Name"
Please Enter Your Name: Ying Li
PS C:\PS> $pw = read-host "Please Enter Your Password"
Please Enter Your Password: Password1
PS C:\PS> $pw
Password1

The password typed and stored as a plain text which is not we would like. How can we mask the password?

PS C:\PS> $pw = read-host "Please Enter Your Password" -AsSecureString
Please Enter Your Password: *********

PS C:\PS> $pw
System.Security.SecureString

The password is typed as * characters and stored as a “SecureString”

Now you may ask, what if I want to know the password?

The following method will get our password back in plain text

PS C:\PS> $BasicString = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw)
PS C:\PS> $pw = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BasicString)
PS C:\PS> $pw
Password1

 

 

Posted: Sep 22 2007, 11:05 PM by yli628 | with no comments
Filed under:

Comments

No Comments