PowerShell Pipeline Input
Pipeline input is a value sent through the pipeline into a function parameter. It lets a function handle each piped item in turn instead of handling the whole list at once.
A plain function misses piped values
Without a process block, the piped names never reach the parameter, so only one empty line prints.
function Show-Item {
param([string]$Name)
"Got: $Name"
}
"Ana", "Ben" | Show-ItemValueFromPipeline plus process handles each item
The marker accepts piped values, and the process block runs once per item.
function Show-Item {
param([Parameter(ValueFromPipeline = $true)][string]$Name)
process {
"Got: $Name"
}
}
"Ana", "Ben" | Show-Itembegin and end run once around the items
The begin block sets up a count, the process block handles each name, and the end block reports the total.
function Show-Items {
param([Parameter(ValueFromPipeline = $true)][string]$Name)
begin {
$count = 0
}
process {
$count++
"Got: $Name"
}
end {
"Total: $count"
}
}
"Ana", "Ben", "Cid" | Show-ItemsExample
function Get-Doubled {
param([Parameter(ValueFromPipeline = $true)][int]$Number)
begin {
$total = 0
}
process {
$total += $Number
$Number * 2
}
end {
"Sum: $total"
}
}
3, 4, 5 | Get-DoubledKey points
- ValueFromPipeline: a marker that lets a parameter accept values from the pipeline.
- process block: the part of a function that runs once for each piped item.
- begin block: the part that runs once before any piped item arrives.
- end block: the part that runs once after the last piped item.
- A plain function without a process block runs once, and the piped values never reach its parameter.
In this example, a function doubles each piped number and adds it to a running total. The begin block starts the total at zero, the process block doubles each number, and the end block prints the sum.
Note
begin and end run once each, even when the pipeline sends many items.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which block runs once for each piped item?