After getting some experience with ParameterSet implementation I can now provide some basic explanation of how they might be used.
ParameterSets - A Simple Explanation
I start the CmdLet code out by adding the optional DefaultParameterSetName attribute to the declaration of the CmdLet Class and set it to the name of the set that I want to use as a default. The name DefaultSet seems appropriate.
<Cmdlet(VerbsCommon.Get, "Computer", _ SupportsShouldProcess:=True, _ DefaultParameterSetName:="DefaultSet")> _ Public Class Get_Computer : Inherits PSCmdlet
I then define the members of my DefaultSet. Currently there is only one named parameter.
<Parameter( _ Position:=0, _ ParameterSetName:="DefaultSet", _ Mandatory:=True)> _ Public Property Name() As String() End Property
I can then add other parameter set names to the CmdLet. I have three more here each with one parameter. Any time I add one of these switches to the CmdLet invocation I will force that ParametSet's rules to be applied. If there are other parameters that are mandatory then they will be checked for by the runtime. Checking will exclude looking for parameters that exist in other sets and only look at the unnamed parameters and the one belonging to the detected named set.
<Parameter( _ ParameterSetName:="FileSet", _ ValueFromPipeline:=True)> _ Public Property File() As System.IO.FileInfo End Property <Parameter( _ ParameterSetName:="DomainSet", _ Mandatory:=False)> _ Public Property Domain() As SwitchParameter End Property <Parameter( _ ParameterSetName:="OUSet", _ Mandatory:=True)> _ Public Property OU() As String End Property
The following is a parameter that has not been given an association with a "named" ParameterSet. It will be available to all parameter sets.
<Parameter( _ Mandatory:=False)> _ Public Property Filter() As SwitchParameter End Property
In my ProcessRecord method I can check to see which parameter set has been validated and take a custom action.
Protected Overrides Sub ProcessRecord() Select Case ParameterSetName Case Is = "DefaultSet" Case Is = "FirstSet" Case Is = "DomainSet" Case Is = "OUSet" Case Is = "FileSet" End Select End Sub
I use a WriteVerbose statement in the BeginProcessing section to help diagnose parameter set detection during code building. The output from this statement will be visible if I add the global CmdLet switch "-verbose" to the CmdLet invocation. ( Get-Computer -verbose)
Protected Overrides Sub BeginProcessing() MyBase.BeginProcessing() WriteVerbose(ParameterSetName) End Sub
Rulez!
- Unnamed parameters belong to all parameter sets.
- A parameter can belong to more than one named parameter set.
More on parameter sets later.
No comments:
Post a Comment