ForEach-Object
Use ForEach-Object to perform an operation on each item in a collection of input objects. See Microsoft.PowerShell.Utility module requirements and examples.
Documentation: Microsoft Learn — ForEach-Object
Syntax
See the command anatomy
Inspect this authored example with fictional data in the bounded browser model. The numbered stages show how its objects change.
Get-Service | ForEach-Object { $_.DisplayName }- Stage 1Get-Service
Positional values or no named parameters - Stage 2ForEach-Object
Positional values or no named parameters
Try it
PowerShell example · browser support is limited.
Execution scope: The full example below requires PowerShell outside this browser. You can edit this runner to use the supported practice commands; unsupported syntax returns an explanation.
Follow the objects
Run the command to inspect each stage.
Examples
Run ForEach-Object
Show reference output
Illustrative output · values vary by environment
2 4 6 8 10
List all with Get-Service
Show reference output
Illustrative output · values vary by environment
Background Intelligent Transfer Service DNS Client Windows Event Log Print Spooler Windows Time Windows Remote Management Windows Update
Parameters
Parameter definitions:
-Process
Practical use and troubleshooting
Practical scenario: Use ForEach-Object when you need to perform an operation on each item in a collection of input objects. Start with one identified target and inspect the returned values before extending the operation to a list. Keep the identity in your report so you can trace each result back to the object or path that produced it.
Common error and fix: A function-like script block returning incidental text can pollute the result. Keep only the transformed value on the success stream and use a diagnostic stream for explanatory messages. In an unattended script, capture this failure with its original error record and record which target failed. An empty result and an unsuccessful query must remain distinguishable in the final report.
See also: Measure-Object. Measure-Object calculates supported aggregates; ForEach-Object processes each input object with a script block. A count or sum is different from returning one transformed result per input. Read the linked command before substituting it; similar names do not imply identical inputs or output.
Recap
ForEach-Object Use ForEach-Object to perform an operation on each item in a collection of input objects. See Microsoft.PowerShell.Utility module requirements and examples.
Next: Where-Object