PowerShell ForEach-Object
ForEach-Object (aliases foreach and %) runs a script block once for each object that arrives through the pipeline. It looks similar to the foreach statement, but it works in the middle of a pipeline and processes objects as they stream in.
'alpha', 'beta', 'gamma' | ForEach-Object { $_.ToUpper() }
1..5 | ForEach-Object { $_ * 10 }ALPHA
BETA
GAMMA
10
20
30
40
50
foreach statement vs ForEach-Object
The word foreach can mean two different things, depending on where it appears:
foreach ($x in $list) { } |
$list | ForEach-Object { } |
|
|---|---|---|
| Kind | language statement | cmdlet in a pipeline |
| Current item | your variable ($x) |
$_ / $PSItem |
| Memory | needs the whole collection first | streams one object at a time |
| Speed | faster for in-memory data | slower per item, but starts immediately |
| Fits in a pipeline | no (wrap it in $( )) |
yes |
break/continue |
normal loop control | stops the whole script, so avoid |
$words = 'pipe', 'stream', 'object'
foreach ($w in $words) { "$w has $($w.Length) letters" }
'---'
$words | ForEach-Object { "$_ has $($_.Length) letters" } | Select-Object -First 2pipe has 4 letters
stream has 6 letters
object has 6 letters
---
pipe has 4 letters
stream has 6 letters
Use the statement for data you already hold in a variable, and the cmdlet in pipelines. Inside ForEach-Object, use return to skip to the next object (it acts like continue).
Begin, Process and End blocks
ForEach-Object accepts three script blocks: -Begin runs once before the first object, -Process for each object, and -End once after the last one:
3, 7, 2, 9 | ForEach-Object -Begin {
$sum = 0
'Starting'
} -Process {
$sum += $_
" added $_ (running total $sum)"
} -End {
"Finished: total $sum"
}Starting
added 3 (running total 3)
added 7 (running total 10)
added 2 (running total 12)
added 9 (running total 21)
Finished: total 21
The same three-block structure appears in advanced functions that accept pipeline input, so it's worth getting used to.
Shortcut forms
To read a property or call a method on each object, pass its name instead of a script block (the "simplified syntax"):
$people = @(
[pscustomobject]@{ Name = 'Ada'; City = 'London' }
[pscustomobject]@{ Name = 'Grace'; City = 'New York' }
)
$people | ForEach-Object Name
$people | ForEach-Object -MemberName City
'hello', 'world' | ForEach-Object ToUpper
'a-b-c', 'x-y' | ForEach-Object Split '-'Ada
Grace
London
New York
HELLO
WORLD
a
b
c
x
y
Running in parallel (PowerShell 7)
ForEach-Object -Parallel runs the script block for several objects at the same time, in separate runspaces. It's useful for slow, independent work such as pinging many servers or calling web APIs. -ThrottleLimit sets how many run at once (default 5).
$results = 1..6 | ForEach-Object -Parallel {
Start-Sleep -Milliseconds (100 * (7 - $_)) # later items finish first
[pscustomobject]@{ Item = $_; Square = $_ * $_ }
} -ThrottleLimit 6
# Parallel results arrive in completion order, so sort before showing them
$results | Sort-Object Item | ForEach-Object { "$($_.Item)^2 = $($_.Square)" }1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
5^2 = 25
6^2 = 36
Inside a parallel block, variables from the calling script aren't visible directly; prefix them with $using:, as in $using:timeout. Parallel runs have overhead, so for fast operations a normal loop is quicker.
Note:
-Paralleldoes not exist in Windows PowerShell 5.1. There you'd use background jobs (see the Remoting & Jobs lesson).
Test yourself
Inside ForEach-Object { ... }, how do you refer to the current object?
- $this
- $_ or $PSItem
- $item
- $args[0]
When does the -End block of ForEach-Object run?
- Before the first object
- For each object
- Once, after the last object
- Only if there is an error
How do you use a variable $limit from the caller inside ForEach-Object -Parallel?
- $limit
- $global:limit
- $using:limit
- $parent:limit