Using c# to write a PowerShell cmdlet that has several parameter sets.
Is there a parameter Type that can be used to qualify/select the required set?
For instance suppose I have these sets of parameters for a Create-IceCream cmdlet:
Create-IceCream [-Choco] .. <insert Choco specific parameters here>
Create-IceCream [-Cherry] .. <insert Cherry specific parameters here>
Create-IceCream .. <insert plain specific parameters here>
What would be the Type for parameters “Choco” and “Cherry”? Obviously a SwitchParameter type can’t be used since it can still be specified with $false value.
An Enum type would not be so intuitive and will require me to create many dynamic parameters.
Any ideas? And I probably should’ve mentioned that for this question let’s assume I’m restricted to creating one cmdlet only.
Thanks,
If you have parameters that are truly unique between sets, then you don’t need a “selector” parameter at all. The “operable” params specified will determine the set on their own. This is the recommended approach, and the way most cmdlets work.
Sometimes it does make it a bit clearer for the user to provide such a parameter, though.
Switchis your best option for this, despite your worries. ParameterSets work entirely by the existence of parameters, they are totally ignorant of the value of any specified params. As such, there is no totally perfect option of any type.Switchprovides the simplest interface available.Users have to be trying pretty hard to mess this up by passing
-Choco:$false, considering the 99% usage of switch parameters is simple present/not-present. And powershell will enforce the parameterset either way, so it’s not possible to pass both-Choco:$false -Cherry:$true.In my experience, very few users even realize you can pass an explicit value to a
Switch, and those who do tend to be more experienced and wouldn’t make that kind of mistake anyway.Edit
Another option is to have a single
-IceCreamTypeparameter which takes either anEnumor a string withValidateSet. It can be a mandatory parameter that is part of all parametersets. Then internally you can interpret remaining shared args as needed. Powershell will complain, however, if it can’t figure out the parameter set based on the args passed, so there is some danger with this approach. You could work around with aDefaultParameterSetName, but after all of this you are starting to lose the value of using parametersets in the first place.