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 %. % is the usual shorthand because foreach is easy to confuse with the foreach statement. Examples:

$names | % {  
    "Hi, my name is $_!"
} 

$names | foreach {  
    "Hi, my name is $_!"
}

Advanced usage

ForEach-Object is a cmdlet, so it takes pipeline input. It accepts three script blocks, like an 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