PowerShell Pipelines
A pipeline is a chain that sends output from one command into the next command. You use a pipeline to hand a set of values to a step that works on each value in turn.
Double each number in a pipeline
The range 1..3 sends three numbers into ForEach-Object. Inside the block, $_ is the current number.
1..3 | ForEach-Object { $_ * 2 }Change each word in a pipeline
Each word passes through the pipeline on its own. The block turns the current word to upper case.
"red", "green", "blue" | ForEach-Object { $_.ToUpper() }Chain two pipeline steps
A pipeline can hold more than two steps. Each step hands its output to the next step.
1..3 | ForEach-Object { $_ * 2 } | ForEach-Object { $_ + 1 }Example
1..4 | ForEach-Object { $_ * 2 }
"cat", "dog" | ForEach-Object { $_.ToUpper() }Key points
- Pipeline: a chain of steps joined so the output of one step becomes the input of the next step.
- The pipeline operator is the vertical bar character, written between two steps.
- The automatic variable $_ stands for the current item passing through the pipeline.
- ForEach-Object is a step that runs a small block of code once for every item it receives.
- Each item prints on its own line unless the code joins the items into one line.
In this example, the first pipeline doubles each number from 1 to 4, printing 2, 4, 6, and 8. The second pipeline turns each word to upper case, printing CAT and DOG.
Note
a pipeline step sees one item at a time, so $_ changes with every item.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does 1..3 | ForEach-Object { $_ * 10 } print?