PowerShell Working with the PowerShell pipeline Writing Functions with Advanced Lifecycle


Example

This example shows how a function can accept pipelined input, and iterate efficiently.

Note, that the begin and end structures of the function are optional when pipelining, but that process is required when using ValueFromPipeline or ValueFromPipelineByPropertyName.

function Write-FromPipeline{
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline)]
        $myInput
    )
    begin {
        Write-Verbose -Message "Beginning Write-FromPipeline" 
    }
    process {
        Write-Output -InputObject $myInput
    }
    end {
        Write-Verbose -Message "Ending Write-FromPipeline"
    }
}

$foo = 'hello','world',1,2,3

$foo | Write-FromPipeline -Verbose

Output:

VERBOSE: Beginning Write-FromPipeline
hello
world
1
2
3
VERBOSE: Ending Write-FromPipeline