powershellpowershell-2.0user-inputsecurestring

How can I use powershell's read-host function to accept a password for an external service?


I have a script I'm writing that makes a connection to a SOAP service. After the connection is made, I need to pass in a the username/pass with every command I send. The problem I have is that when I use read-host to do this, my password is shown in cleartext and remains in the shell:

PS C:\Users\Egr> Read-Host "Enter Pass"
Enter Pass: MyPassword
MyPassword

If I hide it with -AsSecureString, the value can no longer be passed to the service because it is now a System.Security.SecureString object:

PS C:\Users\gross> Read-Host "Enter Pass" -AsSecureString
Enter Pass: **********
System.Security.SecureString

When I pass this, it does not work. I don't care about the passwords being passed to the service in cleartext, I just don't want them sticking around on a user's shell after they enter their password. Is it possible to hide the Read-Host input, but still have the password stored as cleartext? If not, is there a way I can pass the System.Security.SecureString object as cleartext?

Thanks


Solution

  • $Password is a Securestring, and this will return the plain text password.

    [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))