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

扶醉桌前 提交于 2019-11-29 11:00:37

问题


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


回答1:


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

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



回答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



来源:https://stackoverflow.com/questions/15007104/how-can-i-use-powershells-read-host-function-to-accept-a-password-for-an-extern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!