Repost from my old Blog:
In PowerShell I was looking for a way to
let a user enter a password while hiding the characters they typed. My
reason for this is that I wanted to pass it as command line parameter
to an application. I found that the built in Read-Host -assecurestring
would cover the users typing with astricks but the object returned was
a SecureString.
The securestring
object does not have a property or method to allow you to retrieve the
unencrypted string. The reason for this is for security. You need to
explicitly write something if you need to get the string. In many
cases you will be able to provide the SecureString to other objects that will use it for such things as credentials
To get the convert a securestring to a string value you need to first use the Marshal Object to convert the SecureString to a intPtr (pointer). Then use the Marshal's method of PtrToStringAuto to convert the intPtr into a string.
The example code is:
$secret=[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR((read-host
-assecurestring)))
If you found this useful, please click one of the Google links.