Powershell Parameters – Comprehensive Guide to Scripting with Powershell

powershellscriptingshell-scripting

I have a Param block in my script

Param (
    [Parameter(Mandatory=$True)]
    [string]$FileLocation,

    [Parameter(Mandatory=$True)]
    [string]$password = Read-Host "Type the password you would like to set all the users to" -assecurestring
)

Can I use the Read-Host CmdLet in a required Parameter field? if not what can I do to make sure I take in the correct type of variable type so I can pass it to a user creation process?

Best Answer

Specifying correct type for password should be enough, try:

Param (
    [Parameter(Mandatory=$True)]
    [string]$FileLocation,

    [Parameter(Mandatory=$True)]
    [Security.SecureString]$password
)

PowerShell will "mask" password (same as for read-host -asSecureString) and result type will be the one that other cmdlets may require.

EDIT: After recent comments: solution, that gives both option to provide plain text password, or force user to type password (but mask it same way Read-Host -AsSecureString would) and in both cases get [Security.SecureString] in the end. And, as a bonus, you get some fancy prompt for your secret password. ;)

[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}
}

Do-Stuff -With $SecretPassword

I've used Jaykul's trick here to cheat with prompting for secure password. ;) It will make this parameter very hard to use in CLI mode (-Type your secret password won't work as expect), so it should force users of the script to either omit password (and get masked prompt) or specify it with -password parameter that accepts regular string and converts it to secure string inside script logic.