Skip to content

functions that process pipeline parameters

2011/06/01

if a function should process parameters from the pipeline then it has to check if the parameter was passed as a single argument or as an array of arguments (from the pipeline). If it is a pipeline “input” the function has to enumerate the separate items:

Function Do-Something {
 # cmdlet binding let the function act like a cmdlet, 
 # so it can accept the parameters from the 
 # commandline, fill automatically unnamed parameters to
 # positional arguments
  [CmdletBinding()]
  param(
    [Parameter(Mandatory=$True,ValueFromPipeline=$True,
     ValueFromPipelineByPropertyName=$True)]
    [string[]]$paramCanComeFromPipeline
 )

BEGIN {
        $script:i = 0
        <# using the scope "script"otherwise the variable would be only 
        available local in this block
        this is the place where big functions can clear or rename logfiles
        initialize counters for all parameter on the input #>
}

PROCESS {
    <# functions that are called only in the process block
       not visible on the outside #>
    function DoTheJobOnSingleItem {
        param( $SingleItem)

        $script:i+=1
        "run $($script:i) input $SingleItem" | write-host
    }

    # check if we have a pipeline parameter, if so process them one by one
    if ($PSBoundParameters.ContainsKey('paramCanComeFromPipeline')) {
        foreach($SingleItem in $paramCanComeFromPipeline) {
            DoTheJobOnSingleItem –SingleItem $SingleItem
        }
    } else {
        #only a single parameter was given using the -parametername
        DoTheJobOnSingleItem –SingleItem $paramCanComeFromPipeline
    }
}

END { #section where to write summaries and statistics

    }

}
Advertisements

From → arrays, basics, powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: