Optional and Mandatory at the Same Time

by Sep 10, 2014

All PowerShell Versions

Can parameters be optional and mandatory at the same time? They can, based on context.

A parameter can be mandatory when other parameters are present, and optional otherwise.

function Connect-Somewhere
{
 [CmdletBinding(DefaultParameterSetName='A')]
 param
 (
 [Parameter(ParameterSetName='A',Mandatory=$false)]
 [Parameter(ParameterSetName='B',Mandatory=$true)]
 $ComputerName,
 [Parameter(ParameterSetName='B',Mandatory=$false)]
 $Credential
 )
 $chosen = $PSCmdlet.ParameterSetName
 "You have chosen $chosen parameter set."
}

# -Computername is optional
Connect-Somewhere
# here, -Computername is mandatory
Connect-Somewhere -Credential test 

Twitter This Tip! ReTweet this Tip!