4

I have a simple example pieced together from some other posts:

[CmdletBinding(
    DefaultParameterSetName = 'Secret'
)]
Param (
    [Parameter(Mandatory=$True)]
    [string]$FileLocation,

    [Parameter(
        Mandatory = $True,
        ParameterSetName = 'Secret'
    )]
    [Security.SecureString]${Type your secret password},
    [Parameter(
        Mandatory = $True,
        ParameterSetName = 'Plain'
    )]
    [string]$Password
)

if ($Password) {
    $SecretPassword = $Password | ConvertTo-SecureString -AsPlainText -Force
} else {
    $SecretPassword = ${Type your secret password}
}

Write-Host $SecretPassword
$BSTR = `
    [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecretPassword)
    $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
    Write-Host $PlainPassword

https://social.technet.microsoft.com/wiki/contents/articles/4546.working-with-passwords-secure-strings-and-credentials-in-windows-powershell.aspx

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

When running the script how can I make it possible for the entered password to be masked?

So instead of this:

PS C:\temp> .\test.ps1 -FileLocation C:\Temp\file.csv  -Password secret

This

PS C:\temp> .\test.ps1 -FileLocation C:\Temp\file.csv  -Password ******
Community
  • 1
  • 1
dross
  • 1,719
  • 2
  • 14
  • 22

3 Answers3

9

First capture the password using the below statement:

$password = Read-Host "Enter Your Password" -AsSecureString

This will mask the characters entered by the user on the screen.

But you can not use this string directly. In order to use this secure string in your script you need to convert this to a binary string:

$Newpass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

And then use $Newpass as the password entered by the user.

Ajay Pawar
  • 179
  • 6
  • you can prompt for password, receiving password using parameter will not serve your purpose to mask the password. – Ajay Pawar Feb 08 '17 at 08:14
3

To start with, your example isn't going to happen. You are suggesting that you want whatever shell they execute the script from to mask the password, as it is entered as a parameter, before the script even executes. Not happening.

Now, an alternative would be to not accept the password as a parameter, and instead prompt for it every time. In that case you could reduce that entire If($Password) statement to just be:

$SecretPassword = Read-Host 'Type your secret password' -AsSecureString
TheMadTechnician
  • 34,906
  • 3
  • 42
  • 56
2

AsSecureString parameter does this:

-AsSecureString

Indicates that the cmdlet displays asterisks (*) in place of the characters that the user types as input.

4c74356b41
  • 69,186
  • 6
  • 100
  • 141
Richard Szalay
  • 83,269
  • 19
  • 178
  • 237