The ForEach-Object cmdlet works similarly to the foreach statement, but takes its input from the pipeline.
$object | ForEach-Object {
code_block
}
Example:
$names = @("Any","Bob","Celine","David")
$names | ForEach-Object {
"Hi, my name is $_!"
}
Foreach-Object has two default aliases, foreach and % (shorthand syntax). Most common is % because foreach can be confused with the foreach statement. Examples:
$names | % {
"Hi, my name is $_!"
}
$names | foreach {
"Hi, my name is $_!"
}
Foreach-Object stands out from the alternative foreach solutions because it's a cmdlet which means it's designed to use the pipeline. Because of this, it has support for three scriptblocks just like a cmdlet or advanced function:
Example:
"Any","Bob","Celine","David" | ForEach-Object -Begin {
$results = @()
} -Process {
#Create and store message
$results += "Hi, my name is $_!"
} -End {
#Count messages and output
Write-Host "Total messages: $($results.Count)"
$results
}