BudiBadu Logo
Samplebadu

PowerShell by Example: Pipeline

PowerShell 7

Chaining commands with object passing through this code example showing pipe operator for command connection, object property access in pipeline, parameter binding mechanisms, and streaming object processing.

Code

# Pipeline passes objects, not text
Get-Service | 
    Where-Object { $_.Status -eq 'Running' } | 
    Select-Object -First 5 Name, DisplayName

# Sorting and grouping objects
Get-Process | 
    Sort-Object -Property CPU -Descending | 
    Select-Object -First 3

# ForEach-Object for transformations
1..5 | ForEach-Object {
    Write-Host "Processing number: $_"
    $_ * 10
}

# Pipeline variable $_ represents current object
Get-ChildItem | ForEach-Object { $_.FullName }

Explanation

The PowerShell pipeline connects commands using the pipe operator |, but unlike traditional text-based shells that pass strings, PowerShell passes complete .NET objects between commands. This object-oriented pipeline preserves all properties and methods throughout the command chain, eliminating the need for text parsing and enabling sophisticated data manipulation. Objects flow through the pipeline one at a time in a streaming fashion, conserving memory and providing real-time processing.

Parameter binding is the automatic process by which PowerShell associates piped objects with parameters of the receiving cmdlet. This occurs through two mechanisms: ByValue binding matches the object type to a parameter that accepts that type, while ByPropertyName binding matches object property names to parameter names. The pipeline processes each object individually, making it efficient for large datasets as objects are handled sequentially rather than loading everything into memory.

Common pipeline cmdlets include Where-Object (alias ?) for filtering objects based on conditions, Select-Object (alias select) for choosing specific properties or limiting results, Sort-Object for ordering objects by properties, ForEach-Object (alias %) for iterating and transforming objects, and Group-Object for grouping by property values. The automatic variable $_ (or $PSItem in newer versions) represents the current object being processed in the pipeline block.

Code Breakdown

2-4
Pipeline passes service objects, not text, preserving all properties.
3
$_.Status accesses Status property of current pipeline object.
11
ForEach-Object executes script block for each piped object.
17
$_ automatic variable represents current object in pipeline.