🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Pipeline Functions

Pipeline functions are functions that run once for each value sent through a pipeline. A pipeline sends values from one command to the next, and the current value is called $_ inside the function.

A process block runs once per value

This function doubles each value it receives. The numbers 1 to 3 each pass through the process block once.

function Get-Double {
  process { $_ * 2 }
}
1..3 | Get-Double

The current value is $_

Use $_ to work with the value that is passing through right now. Here each word is changed to upper case.

function Get-Shout {
  process { $_.ToUpper() }
}
"hi", "bye" | Get-Shout

A process block can skip values

Output nothing for a value you do not want. Only values greater than 10 come out of this function.

function Get-Big {
  process { if ($_ -gt 10) { $_ } }
}
5, 15, 8, 20 | Get-Big

Example

function Get-Double {
  process { $_ * 2 }
}
function Get-Large {
  process { if ($_ -gt 5) { $_ } }
}
1..5 | Get-Double | Get-Large

Key points

  • Pipeline function: a function that handles values arriving through a pipeline.
  • The process block runs once for each value in the pipeline.
  • Inside the process block, $_ holds the current value.
  • A pipeline function can change each value and send the changed value on.
  • A pipeline function can also skip a value by outputting nothing for it.

In this example, the numbers 1 to 5 first pass through Get-Double and become 2, 4, 6, 8, and 10. Those results then pass through Get-Large, which keeps only the values greater than 5. The printed values are the ones that survive both steps.

Note

without a process block, a function does not run once per pipeline value, so pipeline input needs a process block.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does 1..3 | Get-Double print if Get-Double is defined as process { $_ * 2 }?