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

32,656

Solution 1

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

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

Solution 2

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

Share:
32,656
EGr
Author by

EGr

Updated on February 22, 2020

Comments

  • EGr
    EGr over 4 years

    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
    EGr over 11 years
    That worked, thanks! Out of curiosity, where would I find a solution like this if I were looking on my own?
  • EGr
    EGr over 11 years
    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.
  • Musaab Al-Okaidi
    Musaab Al-Okaidi over 11 years
    Well said @Graimer. I needed to carry out a similar operation a while back, so I searched Google and I found my the answer. :-)