How do I make parameters mandatory in PowerShell?

Solution 1:

You specify it in an attribute above each parameter like this:

function Do-Something{
    [CmdletBinding()]
    param(
        [Parameter(Position=0,mandatory=$true)]
        [string] $aMandatoryParam,
        [Parameter(Position=1,mandatory=$true)]
        [string] $anotherMandatoryParam)

    process{
       ...
    }
}

Solution 2:

To make a parameter mandatory add a "Mandatory=$true" to the parameter description. To make a parameter optional just leave the "Mandatory" statement out.

This code works for both script and function parameters:

[CmdletBinding()]
param(
  [Parameter(Mandatory=$true)]
  [String]$aMandatoryParameter,

  [String]$nonMandatoryParameter,

  [Parameter(Mandatory=$true)]
  [String]$anotherMandatoryParameter

)

Make sure the "param" statement is the first one (except for comments and blank lines) in either the script or the function.

You can use the "Get-Help" cmdlet to verify the parameters have been defined correctly:

PS C:\> get-help Script.ps1 -full
[...]
PARAMETERS
    -aMandatoryParameter <String>

        Required?                    true
        Position?                    1
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -NonMandatoryParameter <String>

        Required?                    false
        Position?                    2
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

    -anotherMandatoryParameter <String>

        Required?                    true
        Position?                    3
        Default value
        Accept pipeline input?       false
        Accept wildcard characters?

Solution 3:

just wanted to post another solution, since i find param(...) blocks kind of ugly. looks like this code:

function do-something {
    param(
        [parameter(position=0,mandatory=$true)]
        [string] $first,
        [parameter(position=1,mandatory=$true)]
        [string] $second
    )
    ...
}

can also be written more concisely like this:

function do-something (
        [parameter(mandatory)] [string] $first,
        [parameter(mandatory)] [string] $second
    ) {
    ...
}

which looks much nicer! the =$true can be omitted because mandatory is a switch parameter.

(disclaimer: i'm pretty new to PS, and it's possible that this solution has some corner case i'm not aware of. if so, please let me know!)

Solution 4:

You don't have to specify Mandatory=true, Mandatory is enough.

Simple Example:

function New-File
{
    param(
        [Parameter(Mandatory)][string]$FileName
    )

    New-Item -ItemType File ".\$FileName"
}