Determine Functions Pipeline Position with PowerShell

by Sep 26, 2012

Assume your function wanted to know whether it is the last element in a pipeline or operating in the middle of it. Here is a way for a function to determine its current pipeline position:

function test {
    param( [Parameter(ValueFromPipeline=$true)]$data )

    process {
    if ($MyInvocation.PipelinePosition -ne $MyInvocation.PipelineLength) {
            $data
        } else {
            Write-Host $data -foreground Red -background White
        }
    }
}

1..3 | test
1..3 | test | Get-Random -count 3

"test" will output the data in red color when it is the last element (thus controlling presentation itself) whereas it forwards the data if it is not the last pipeline command.

Twitter This Tip! ReTweet this Tip!