38

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

EGr
  • 2,072
  • 10
  • 41
  • 61

3 Answers3

61

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

[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Password))
Musaab Al-Okaidi
  • 3,734
  • 22
  • 21
  • That worked, thanks! Out of curiosity, where would I find a solution like this if I were looking on my own? – EGr Feb 21 '13 at 18:18
  • 1
    Well said @Graimer. I needed to carry out a similar operation a while back, so I searched Google and I found my the answer. :-) – Musaab Al-Okaidi Feb 21 '13 at 18:54
3

You can save the password(input) as a variable and pass it to your service. If the code is run in a script or as a function, the variable containing the password will be deleted after it's done(they are stored in a temp. local scope). If you run the commands in the console(or dot-source the script like . .\myscript.ps1), the password variable will stay in the session scope, and they will be stored until you delete it or close the session. If you want to be sure the variable is removed after your script is run, you can delete it yourself. Like this:

#Get password in cleartext and store in $password variable
$password = Read-Host "Enter Pass"

#run code that needs password stored in $password

#Delete password
Remove-Variable password

To read more about how variables are stored in scopes, check out about_Scopes

Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • 3
    I suppose I wasn't 100% clear. I don't want the password to be visible on the shell, so if someone was walking by they wouldn't be able to see the password. – EGr Feb 21 '13 at 18:21
3

There is a way to do this in PowerShell versions 6.x+:

$password = Read-Host -MaskInput "Enter password"
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Rafael Kitover
  • 967
  • 10
  • 13