19

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?

miguelbgouveia
  • 2,963
  • 6
  • 29
  • 48
Tobias
  • 193
  • 1
  • 1
  • 5
  • 1
    http://stackoverflow.com/questions/15007104/how-can-i-use-powershells-read-host-function-to-accept-a-password-for-an-extern – David Brabant Nov 09 '16 at 09:13

1 Answers1

29

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)
Martin Brandl
  • 56,134
  • 13
  • 133
  • 172
  • 1
    You should also free the unmanaged memory afterwards, as stated by the [documentation](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.securestringtobstr#remarks): `[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)` – dimizuno Jun 15 '23 at 20:05