PowerShell ForEach-Object


Example

The ForEach-Object cmdlet works similarly to the foreach statement, but takes its input from the pipeline.

Basic usage

$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 $_!"
} 

Advanced usage

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:

  • Begin: Executed once before looping through the items that arrive from the pipeline. Usually used to create functions for use in the loop, creating variables, opening connections (database, web +) etc.
  • Process: Executed once per item arrived from the pipeline. "Normal" foreach codeblock. This is the default used in the examples above when the parameter isn't specified.
  • End: Executed once after processing all items. Usually used to close connections, generate a report etc.

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
}