ForEach Object - PowerShell
Overview
ForEach-Object processes each element of an array or other object collection, executing a script block for each item. It is a powerful tool for automating tasks involving individual elements within a collection.
Syntax
ForEach-Object [-Process {}] [-Begin {}] [-End {}] [[-FilterScript {}] -Exclude | -Include] [-Parallel] [-ThrottleLimit <int>] [-AsJob] [-SyncJob] [-WhatIf] [-Confirm] [-ErrorAction <Action>] [-ErrorVariable <Variable>] [-WarningAction <Action>] [-WarningVariable <Variable>] [-InformationAction <Action>] [-InformationVariable <Variable>] [-Verbose] [-Debug] [-OutVariable <Variable>] [-OutFile <String>]
Options/Flags
- -Process: Script block to execute for each element.
- -Begin: Script block to execute before processing the first element.
- -End: Script block to execute after processing the last element.
- -FilterScript: Script block to filter elements.
- -Exclude: Exclude elements that match the filter.
- -Include: Include only elements that match the filter.
- -Parallel: Run the script block in parallel for each element.
- -ThrottleLimit: Maximum number of concurrent pipeline operations allowed.
- -AsJob: Create a job that runs the script block.
- -SyncJob: Wait for the job to complete before continuing.
- -WhatIf: Display what would happen without actually executing the script block.
- -Confirm: Prompt for confirmation before executing the script block.
- -ErrorAction: Action to take when an error occurs.
- -ErrorVariable: Variable to store error messages.
- -WarningAction: Action to take when a warning occurs.
- -WarningVariable: Variable to store warning messages.
- -InformationAction: Action to take when informational messages occur.
- -InformationVariable: Variable to store informational messages.
- -Verbose: Display verbose output.
- -Debug: Display debug output.
- -OutVariable: Variable to store output.
- -OutFile: File to write output to.
Examples
Iterate over an array and display each element:
$array = 1, 2, 3, 4, 5
$array | ForEach-Object { Write-Host $_ }
Filter elements based on a condition:
$array | ForEach-Object -FilterScript { $_ -gt 2 }
Process elements in parallel:
$array | ForEach-Object -Parallel { Write-Host $_ }
Create a job:
$job = $array | ForEach-Object -AsJob { Write-Host $_ }
Common Issues
- Script block not defined: Ensure the
-Process
parameter is specified with a valid script block. - Object not iterable: The input object must be an array or other iterable collection.
- Parallel processing errors: If parallel processing fails, try reducing the
-ThrottleLimit
or using-AsJob
instead.
Integration
Combine with Where-Object
for filtering:
$results = $array | Where-Object { $_ -gt 2 } | ForEach-Object { Write-Host $_ }
Create custom objects:
$objArray = $array | ForEach-Object { New-Object -TypeName CustomObject -Property @{ Value = $_ } }