ForEach-Object

suggest change

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:

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
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents