Industrial Strength Functions in PowerShell V2 CTP 3

With PowerShell V2 we can now get nearly all the functionality of the PowerShell engine that is available to Cmdlet developers that are using C#. Granted, if you haven’t written any Cmdlets in C#, you probably don’t understand the power that this brings, but trust me, its huge!

Here are just a couple things to think about as we start to build more industrial strength functions. We can do all kinds of cool things with parameters now. We can validate that the entry matches a regular expression. We can tell the parameter to accept a value from the pipeline. We can declare whether or not a parameter is mandatory or not.

In addition to tons of flexibility with parameters, we can also leverage the built in help for functions that we write. Rather than going on and listing every single feature, let me just give an example of what I am talking about.

   1: Function Get-EvenNumber {
   2: #.Synopsis
   3:     #    Returns even numbers using the Modulo operator
   4: #.Description
   5:     #    takes a set of numbers and tells you which ones are even
   6: #.Parameter number
   7:     #    An integer that is required, can take values from the pipeline as well   
   8: #.Example
   9:     #    1..10 | Get-EvenNumber
  11: param (
  12:    [Parameter(Position=0, 
  13:               Mandatory=$true, 
  14:               ValueFromPipeline=$true, 
  15:               HelpMessage="Please type a number between 1 and 10")]
  16:    [Alias("integer")]
  17:    [int]
  18:    $number
  20: )
  21: begin {"Begining of Pipeline"}
  23: process {
  24:          if (($number % 2) -eq 0) {"$number is even"}
  25:         }
  27: end {"End of Pipeline"}
  29: }

Now here are some screen shots of how you can use this function, just like a Cmdlet in version 1.

In this first one, we first use the function with a parameter, and then in the pipeline.

In the function, we used the Begin, Process, and End Blocks, so we can do stuff before we send anything down the pipeline, then work on the pipeline objects, and then do anything else we need to do to wrap up. This is why you see the text “Beginning Pipeline” and “End of Pipleline".” This is for demonstration purposes only.


Because we declared that the number parameter is mandatory and we specified a help message, we get this great interactivity for only setting a couple attributes. PowerShell tells the user, “You forgot this mandatory paramter, and if you need help, type !? and you can see what the function author wants you to know about the parameter. Pretty flippin’ awesome! 


And finally , of course we get the following when we type help get-evennumber because of all the great code commenting we did at the beginning of the function. Notice how nicely its formatted. It even automagically pulls all the parameters and their types for you in the SYNTAX section.


Comments are closed