A common scripting requirement is to loop through a collection of items (files, registry entries etc.)
Pipelines provide an easy way to achieve this, for example consider the following script:
$a = Get-ChildItem *.txt foreach ($file in $a) { if ($file.length -gt 100) { Write-Host $file.name } }
Rewriting this with a pipeline it becomes a one liner:
Get-ChildItem *.txt | where {$_.length -gt 100} | Format-Table name
To chain commands together into a pipeline, specify each command in the order that they should run (left to right).
Separate the commands with a pipe symbol (|).
The commands will pass the necessary objects down the pipeline as part of a single operation.
The $_ is a variable created automatically by PowerShell to store the current pipeline object. All properties of the pipeline object can be accecced via this variable.
In PowerShell 3.0 and above a new automatic variable called $PSItem is available, this is exactly the same as $_
It just provides an alternative name to make your pipeline code easier to read.
“Pipe Dream": An unrealistic hope or fantasy - The allusion is to the dreams experienced by smokers of opium pipes.
Related PowerShell Cmdlets:
parameters - Command Line Parameters param() and $args[]
ForEach-Object - Loop for each object in the pipeline.
ForEach - Loop through values in the pipeline.