Mutually Exclusive Parameters (Part 2)

by May 13, 2015

Mutually exclusive parameters in PowerShell functions use the "ParameterSetName" attribute to assign parameters to different parameter sets (or groups of parameters).

A little known fact is that you can assign multiple parameter set names to one parameter. This way, a parameter could be optional in one scenario, and mandatory in another.

function Test-ParameterSet
{
  [CmdletBinding(DefaultParameterSetName='NonCredential')]
  param
  (
    $id,

    [Parameter(ParameterSetName='LocalOnly', Mandatory=$false)]
    $LocalAction,

    [Parameter(ParameterSetName='Credential', Mandatory=$true)]
    [Parameter(ParameterSetName='NonCredential', Mandatory=$false)]
    $ComputerName,

    [Parameter(ParameterSetName='Credential', Mandatory=$false)]
    $Credential
  )

  $PSCmdlet.ParameterSetName
  $PSBoundParameters

  if ($PSBoundParameters.ContainsKey('ComputerName'))
  {
    Write-Warning 'Remote Call!'
  }
}

The function Test-ParameterSet shows how to do this: -ComputerName is optional when the parameter set "NonCredential" is active. If a user uses the -Credential parameter, -ComputerName becomes mandatory. And if the user picks the -LocalAction parameter, neither -ComputerName nor -Credential is available anymore.

Twitter This Tip! ReTweet this Tip!