Tome's Land of IT
IT Notes from the Powertoe – Tome Tanasovski
Powerbits #2 – Read-Host -AsSecureString
April 23, 2010
Posted by on Read-Host is a great little cmdlet that gives you a very simple way of getting user input into your script. On occasion you may have sensitive information being input that you don’t want pesky over-the-shoulder guests to see. The most obvious time is when you need to grab a password from the user of your script. Read-Host has a nice way of hiding the information with the -AsSecureString parameter:
-AsSecureString changes the output of the cmdlet from a String to a SecureString. Generally this will be fine because you will probably be passing the captured output to another cmdlet that expects a SecureString, but this may not always be the case. Perhaps you have a database user account that you want to gather the password for and then create a connection string within your script. In this case a SecureString is not what you want. So how do you convert a SecureString to a String? The answer is this Powerbit:
$password=read-host -assecurestring $decodedpassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Thanks! You saved me a huge headache!