Tobias
Tobias

Reputation: 203

Is it possible to hide the user input from read-host in Powershell?

I´m looking for a way to hide the user input from the Read-Host cmdlet.

I know I can do this with -assecurestring, but I´d like to save the input as plain text in my variable.

Is there a possible way to do this?

Upvotes: 20

Views: 29798

Answers (2)

Carl Walsh
Carl Walsh

Reputation: 6999

I wasn't sure how to use -AsSecureString as macOS with the new pwsh (I don't know if marshalling BSTR on *nix is supported, as PtrToStringAuto() only returned the first char of the password).

Now there's a much simpler option -MaskInput:

$ Read-Host "Password" -MaskInput
Password: ****
abcd

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 59001

You have to use the -AsSecureString switch but you can also retrieve the plaintext value:

$securedValue = Read-Host -AsSecureString
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securedValue)
$value = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)

# then free up the unmanged memory afterwards (thank to dimizuno)
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)

Upvotes: 30

Related Questions