powershellinputhidepowershell-cmdlet

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?


Solution

  • 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)