How-to: Use the PowerShell Pipeline.

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. It is important to emphasise that these are full rich data objects not simple items of text as they would be in a unix shell.

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.

Some common destinations for piped output:

| Format-Table -Property name,value -wrap   Prettify the output.
| Out-Host -paging   View the output a page at a time (like the less utility in unix)
| Get-Member   View all the methods & properties.

“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.


 
Copyright © 1999-2024 SS64.com
Some rights reserved