Here’s some code that I absolutely know I’m going to need again in the future, what better place to put it than on my blog!
If you need to prompt the user for a password when using Powershell then you want to make sure that the value types in isn’t visible on the screen. That’s quite easy using the –AsSecureString parameter of the Read-Host cmdlet however its not quite so easy to retrieve the supplied value. The following code shows how to do it:
$response = Read-host "What's your password?" -AsSecureString
$password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($response)
I don’t know of a quick and easy way to format Powershell code for a blog post so here’s a screenshot instead:
I’ve also put this on pastebin: http://pastebin.com/2D6xaz0U
All credit goes to Paul Williams for his post Converting System.Security.SecureString to String (in PowerShell)