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

2

20

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?

Asocial answered 9/11, 2016 at 9:10 Comment(1)
#15007604Downfall
T
30

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)
Torrie answered 9/11, 2016 at 9:13 Comment(1)
You should also free the unmanaged memory afterwards, as stated by the documentation: [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)Konikow
B
1

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
Bruxelles answered 3/2, 2024 at 0:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.