My Technical Notes

Monday, 4 May 2015

PowerShell: Accepting pipelined input and from parameter

Below is a pattern for defining a PowerShell function that will accept input from the pipeline, but will also accept via a parameter if it is specified that way instead:


Function MyFunction {
    param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]$ObjectSet
    ) 
    
    if ($input) {
        $ObjectSet = $input
    }

    # now use $ObjectSet
}

Now I can pass data to `MyFunction` in two ways, either by the pipeline:


dir | MyFunction
or as a parameter to it:

MyFunction (dir)

If I wish to lazy process the input, then I would use a process block in which I iterate over `$ObjectSet`. Note that `$ObjectSet` is the current pipeline object `$_` if we use the pipeline input. Doing a `foreach` on a singular object is no different to doing a foreach on an array containing only one element. Therefore we iterate over `$ObjectSet`:


Function MySecondFunction {

    param(
    [Parameter(Mandatory=$true,ValueFromPipeline=$true)]$ObjectSet
    ) 

    process {
        foreach ($o in $ObjectSet) {
            # use $o here
        }   
    }
}

No comments: