ForEach-Object is a PowerShell CmdLet that processes each object coming through the pipeline one at a time. It is the standard way to run a script block against every item in a pipeline stream.
Syntax
<command> | ForEach-Object { <script block using $_> }
$_is the automatic variable representing the current object in the pipeline.- The script block
{ }is executed once per input object.
Example from the book
The example in the book combines Get-Process and Get-NetTCPConnection into a single pipeline:
Get-Process -Name chrome | ForEach-Object {
Get-NetTCPConnection -State Established -OwningProcess $_.Id -ErrorAction SilentlyContinue
}
For each Chrome process, the script block uses $_.Id to pass that process's ID to Get-NetTCPConnection.
Alias
% is a shorthand alias for ForEach-Object:
Get-Process -Name chrome | % { $_.Id }
ForEach-Object vs foreach
ForEach-Object |
foreach |
|---|---|
| CmdLet used in pipelines | Language statement used in scripts |
| Processes streaming input | Iterates over a collection in memory |
ForEach-Object is essential for building single-pipeline solutions that avoid intermediate variables.
Common use cases
- Running a command for each object in a pipeline.
- Accessing nested properties of piped objects, similar to Select-Object.
- Building PowerShell Custom Objects from pipeline data.
Example:
Get-Process | ForEach-Object {
[PSCustomObject]@{
Name = $_.Name
Id = $_.Id
}
}