I just realized that I have failed to note that, so far, all examples have been given in VB.NET syntax. This has happened because I started this little project when I was trying to convert a CmdLet into VB.NET. As I was working with the Attributes I noticed that, in the SDK, not one scrap of code has been given in VB.NET and that the conversions were not completely obvious to all.
For C# CmdLet builders the SDK has all of the necessary syntaxes and examples. Hopefully my discussion will be of value to beginners with CmdLets in C#.
Now for more fun with CmdLet Parameters, this time with a no-attribute, no-argument parameter.
The Switch Parameter
This is one of my favorite. It is easy to build and easy to use. It also comes in very handy when building CmdLets that run mostly from the command line but will work well with pipelines.
<Parameter( _ )> _ Public Property Detailed() As SwitchParameter
The SwitchParameter property type can be declared as simply as above. It is a Boolean and requires no input after the switch. You use it by adding it to the command line anywhere after the CmdLet
PS>Test-CmdLet mytest -detailed
This will set the property to True. Not using the switch parameter will leave it at False, the default.
PS>Test-CmdLet mytest -detailed Name : mytest Host : Detailed : True Stopping : False CommandRuntime : Test-Cmdlet PS>Test-CmdLet mytest Name : mytest Host : Detailed : False Stopping : False CommandRuntime : Test-Cmdlet
The Rest Of The Line Parameter Value
<Parameter( _
ValueFromRemainingArguments:=True) _
> _
By using ValueFromRemainingArguments we can get a list from the command line. This is useful when we want to specify a few quick items such as user ids or computer names. Larger lists should probably always be taken from a file or from the pipeline.
Here is one of the ways this parameter value can be used.
PS>Test-Cmdlet -host alpha,beta,gamma,delta Name : Host : {alpha, beta, gamma, delta} Detailed : False Stopping : False CommandRuntime : Test-Cmdlet PS>get-bufferhtml 25 >d:\buffer.txt
The Host property is populated with an array of all of the strings on the remainder of the command line. This can be used in any way you need to make a CmdLet that is flexible from the command line and in the pipeline.
In the next installment I am going to try and tackle ParameterSets. We have enough pieces here to begin to experiment with how ParameterSets can add to the flexibility of a CmdLet.
Here is a hook into the online SDK docs about using ParameterSets and Parameters.
No comments:
Post a Comment