Sometimes PowerShell functions need to be mutually exclusive, allowing users to select only one or two of them.
To create a set of mutually exclusive arguments to the script, you can give them different attribute flags and ensure their uniqueness (assuming that the parameter type is not recognized automatically).
function Test-parameterset
{
[cmdletbinding (defaultparametersetname= ' number ')]
param
(
[int ]
[Parameter (parametersetname= ' number ', position=0)]
$id,
[string]
[Parameter (parametersetname= ' Text ', position=0)]
$name
)
$PSCmdlet. Parametersetname
$PSBoundParameters
}
The above function has two parameters,-id and-name. Users can only use one of them and not both. At the same time here The example also teaches how to get the user input parameters.
Multiple mutex parameters can be distinguished by "parametersetname" to distinguish between different parameter settings (also including collection parameters)
In fact, you can also assign multiple parameters to a parameter, a fixed parameter and an optional parameter.
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 Test-parameterset function tells you that when you use "noncredential",-computername is optional, and when the user uses the "-credential" parameter "-computername" becomes a required parameter, if you use the " -localaction "parameter, you will not be able to use-computername and-credential.