Tome's Land of IT

IT Notes from the Powertoe – Tome Tanasovski

Powerbits #2 – Read-Host -AsSecureString

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))
Advertisements

One response to “Powerbits #2 – Read-Host -AsSecureString

  1. Shai Perednik (@shaiss) January 12, 2012 at 3:57 pm

    Thanks! You saved me a huge headache!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: