Custom PowerShell functions, when setting parameters, can be set to optional in some cases, and are set to required under certain conditions.
The sample code is copied from the Web site.
1 functionconnect-somewhere2 {3[Cmdletbinding (Defaultparametersetname=' A ')]4 param5 (6[Parameter (Parametersetname= ' A ', mandatory=$false)]7[Parameter (Parametersetname= ' B ', mandatory=$true)]8 $ComputerName,9[Parameter (Parametersetname= ' B ', mandatory=$false)]Ten $Credential One ) A $chosen=$PSCmdlet. Parametersetname -"You have chosen$chosenparameter set. " -}
An example function defines two parameter sets: A, B.
Parameter set A has only one parameter $computername, and it is optional.
Parameter set B has two parameters $computername and $credential.
If you use the default parameter set a, the function does not need to enter the ComputerName parameter because it is not required.
If the parameter $credential is used, the parameter set is assigned a value of B, at which point the $computername property mandatory=$true, forcing $computername to be used.
The following example shows a more detailed illustration:
1 functiontest-Parameterset2 {3[Cmdletbinding (Defaultparametersetname =' noncredential ')]4 param5 (6 $id,7 8[Parameter (parametersetname = ' localonly ', Mandatory =$false)]9 $LocalAction,Ten One[Parameter (parametersetname = ' credential ', Mandatory =$true)] A[Parameter (parametersetname = ' noncredential ', Mandatory =$false)] - $ComputerName, - the[Parameter (parametersetname = ' credential ', Mandatory =$false)] - $Credential - ) - + $PSCmdlet. Parametersetname - $PSBoundParameters + A if($PSBoundParameters. ContainsKey (' ComputerName ')) at { -write-Warning ' Remote call ' - } -}
PowerShell Parameterset parsing