In PowerShell, I want to write a function, that accepts different options as parameters. It is OK, if it receives more than one parameter, but it has to receive at least one parameter. I want to enforce it through the parameter definition and not through code afterwards. I can get it to work with the following code:
function Set-Option {
Param(
[Parameter(Mandatory, ParameterSetName="AtLeastOption1")]
[Parameter(Mandatory=$false, ParameterSetName="AtLeastOption2")]
[Parameter(Mandatory=$false, ParameterSetName="AtLeastOption3")]
$Option1,
[Parameter(Mandatory=$false, ParameterSetName="AtLeastOption1")]
[Parameter(Mandatory, ParameterSetName="AtLeastOption2")]
[Parameter(Mandatory=$false, ParameterSetName="AtLeastOption3")]
$Option2,
[Parameter(Mandatory=$false, ParameterSetName="AtLeastOption1")]
[Parameter(Mandatory=$false, ParameterSetName="AtLeastOption2")]
[Parameter(Mandatory, ParameterSetName="AtLeastOption3")]
$Option3
)
# Do stuff, but don't evaluate the plausibility of the given parameters here
}
But as you can see, it scales badly. For each additional option, I have to add a line to all other options. Can this be done in a more efficient and a more maintainable way?
As I already said, I don't want to check the parameters in the code, e. g. through evaluating $PSBoundParameters
. I want it to happen in the parameter definition for auto-doc reasons.
If you need a real world example, have a look at Set-DhcpServerv4OptionValue
which accepts many different options (-DnsDomain
, -DnsServer
, -Router
, ...), where it is OK to have them all, but it makes no sense to have none.
Note: After several answers have already been provided, I just realized that my code is actually not working, if you provide more than one option.