Thursday, November 04, 2010

PowerShell: Advanced Functions (Script CmdLets)

PowerShell calls ‘Script CmdLets’ Advanced Functions.

At a PowerShell prompt type:  help about_advanced_functions

Here is a minimal advanced function that can be used as a CmdLet.   The minimum requirement is to have either [CmdletBinding()] or at least one [Parameter()] statement.

1 function Test-MyCmdLet( 2 [cmdletBinding()] 3 [parameter( 4 ValueFromPipeline=$true 5 ) 6 ]$whatever 7 ){ 8 9 process{ 10 $whatever 11 } 12 }

Now we are sure that the function will be recognized as a CmdLet and not just a regular function.

What does this buy us in PowerShell?  Not much. We can call the function and be prompted for input if we mark this as a ‘Mandatory’ parameter.


Now we will be prompted if we don’t provide an argument.

We can also add ‘help’ to the prompt like this:

     HelpMessage=”Please enter a value for this parameter

Now we will be prompted with this more specific message.

All of this is very nice but it really doesn’t buy much in the way of processing.  What we would really like to do is have the function accept values directly from the pipeline.  To accomplish this we can just add an attribute:

     HelpMessage=”Please enter a value for this parameter,

Now we can pump items in the pipeline directly through the function.

Get-Process  |Test-MyCmdLet

Get-Process | Select-Object processname, handles | Test-MyCmdLet | ft -auto

This will allow us to build pipeline smart functions that can easily add custom processing to our PowerShell scripts.

Next: The Pipeline

No comments:

Post a Comment