How do I make parameters mandatory in PowerShell?

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{
       ...
    }
}

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?

Tags:

Powershell