Reputation: 101
I want to make all parameters in a parameterset mandatory, but only if one of the parameters is actually specified (all or none situation).
So i want to be able to call my function as either Test-Mandatory -Param1
or Test-Mandatory -Param1 -Param2 -Param3
. So when i specify Param2, i want Param3 to be mandatory, and vice versa.
I would have thought that the something as the following would achieve this:
Function Test-Mandatory
{
Param
(
[switch]$Param1,
[Parameter(ParameterSetName='Set1', Mandatory)]
[switch]
$Param2,
[Parameter(ParameterSetName='Set1', Mandatory)]
[switch]
$Param3
)
}
However, when i use the above, i cannot call the function as Test-Mandatory -Param1
, as it will prompt me to provide a value for param2/param3.
I know i could add another parameter, add this to the set, and make it non mandatory, this would enable me to switch between the parametersets using the switch, but i would rather not do that.
Is there another way to solve this that i am overlooking?
Upvotes: 0
Views: 437
Reputation: 13191
Create two parameter sets: one with Param1 only and second with all three parameters. Since you can specify every parameter only once inside Param(), you can do that by adding two set attributes to Param1.
Function Test-Mandatory
{
[CmdletBinding(DefaultParametersetName='Set1')]
Param
(
[Parameter(ParameterSetName='Set1', Mandatory=$true)]
[Parameter(ParameterSetName='Set2', Mandatory=$true)]
[switch]$Param1,
[Parameter(ParameterSetName='Set2', Mandatory=$true)]
[switch]$Param2,
[Parameter(ParameterSetName='Set2', Mandatory=$true)]
[switch]$Param3
)
}
Test-Mandatory -Param1 # works
Test-Mandatory -Param1 -Param2 # asks for param3
Upvotes: 0