Partilhar via


Microcode: PowerShell Scripting Trick - Writing functions that use the pipeline or take arguments

I was cleaning up some scripts for posting when I happened upon this minor trick. I had a function that was using $input, a PowerShell v1 feature that allows you to use pipelined values within a function.  This enables you to do basic pipelining with PowerShell v1, but it can make code more complex if you want to handle the same item as one or more positional parameters.

Here's a simplified example:

function Add-Number() {
    begin { $total = 0 }
    process {
        foreach ($in in $input + $args) {
            # Expand once more to handle lists of lists
            foreach ($i in $in) {
                $total+=$i
            }
        }
    }
    end { $total }
}

This snippet of code allows your V1 functions to act significantly more like cmdlets will, without needing to use PowerShell CTP2.

It makes

1..5  | Add-Number

work the same as:

Add-Number (1..5)

and the same as:

Add-Number 1 2 3 4 5

Since every item in PowerShell is an object, you can also easily check for types at any point, which allows you to respond to multiple types of objects in a pipeline.  This simple trick makes it much easier to build V1 functions that have most of the flexibility of cmdlets.

Hope this helps,

James Brundage