PowerShell Pipeline Input
The functions you've written so far get their data from parameters. Real PowerShell commands also accept data from the pipeline, so they can be chained: Get-ChildItem | Your-Function | Export-Csv. This lesson shows how to make your advanced functions pipeline-aware.
ValueFromPipeline and the process block
Mark a parameter with ValueFromPipeline and put the per-object code in a process block. PowerShell runs process once for every object that arrives:
function ConvertTo-Celsius {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[double]$Fahrenheit
)
process {
[math]::Round(($Fahrenheit - 32) * 5 / 9, 1)
}
}
32, 50, 98.6, 212 | ConvertTo-Celsius
ConvertTo-Celsius -Fahrenheit 4510
10
37
100
232.8
The same function also works with a normal argument. Without a process block, only the last pipeline object would be processed, a very common bug.
begin, process, end
Like ForEach-Object, a function may have three blocks:
| Block | Runs | Typical use |
|---|---|---|
begin |
once, before the first object | set up counters, open connections |
process |
once per pipeline object | the real work |
end |
once, after the last object | totals, summaries, cleanup |
function Measure-Words {
[CmdletBinding()]
param([Parameter(ValueFromPipeline)][string]$Line)
begin { $lines = 0; $words = 0 }
process {
$lines++
$words += @($Line -split '\s+' | Where-Object { $_ }).Count
}
end { "$lines lines, $words words" }
}
@(
'PowerShell pipes objects'
'functions can join the pipeline'
'with a process block'
) | Measure-Words3 lines, 12 words
Arrays: pipeline vs parameter
If a parameter is typed as an array ([string[]]), callers may also pass several values directly. Loop over the parameter inside process so that both ways work:
function Get-Initial {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipeline)]
[string[]]$Name
)
process {
foreach ($n in $Name) {
"$n -> $($n.Substring(0, 1).ToUpper())"
}
}
}
'ada', 'grace' | Get-Initial
Get-Initial -Name 'linus', 'margaret'ada -> A
grace -> G
linus -> L
margaret -> M
When piped, $Name holds one value per process call; when passed as an argument, it holds the whole array in a single call. The inner foreach handles both.
Binding by property name
ValueFromPipelineByPropertyName takes the parameter's value from a property with the same name on the incoming object. This lets your function consume objects from other commands (or from CSV files) without any glue code:
function New-Mailbox {
[CmdletBinding()]
param(
[Parameter(Mandatory, ValueFromPipelineByPropertyName)]
[string]$UserName,
[Parameter(ValueFromPipelineByPropertyName)]
[Alias('Dept')]
[string]$Department = 'General'
)
process {
"mailbox $($UserName.ToLower())@example.com ($Department)"
}
}
$newHires = @(
[pscustomobject]@{ UserName = 'Ada'; Dept = 'Research' }
[pscustomobject]@{ UserName = 'Linus'; Dept = 'Kernel' }
[pscustomobject]@{ UserName = 'Grace' }
)
$newHires | New-Mailboxmailbox ada@example.com (Research)
mailbox linus@example.com (Kernel)
mailbox grace@example.com (General)
The [Alias('Dept')] attribute lets the Dept property bind to -Department. Grace has no Dept, so the default applies.
Data from CSV straight into a function
Because Import-Csv and ConvertFrom-Csv create objects with one property per column, a CSV file can drive a by-property-name function directly:
function Test-Port {
[CmdletBinding()]
param(
[Parameter(ValueFromPipelineByPropertyName)][string]$Host_,
[Parameter(ValueFromPipelineByPropertyName)][int]$Port
)
process {
$status = $Port -in 22, 80, 443 ? 'standard' : 'custom'
'{0,-8} {1,5} {2}' -f $Host_, $Port, $status
}
}
@'
Host_,Port
web01,443
db01,5432
jump,22
'@ | ConvertFrom-Csv | Test-Portweb01 443 standard
db01 5432 custom
jump 22 standard
($Host is a reserved automatic variable, which is why this example uses Host_.)
Tip: Output objects from
processas soon as you have them instead of collecting everything and returning it inend. That keeps your function streaming, so| Select-Object -First 1stays fast.
Test yourself
A pipeline function has no process block. What happens when 5 objects are piped in?
- All 5 are processed
- Only the last object is processed
- Only the first object is processed
- An error
What does ValueFromPipelineByPropertyName do?
- Binds the whole object
- Binds the value of the incoming object's property with the same name as the parameter
- Sorts input by property name
- Prints property names
Which block is the right place to print a final summary?
- begin
- process
- end
- param