ForEach - PowerShell


ForEach is a PowerShell command that iterates through a specified collection of objects and performs a set of actions on each object in the collection. It enables you to process items in a list, array, or other collection in a loop-like manner, making it versatile for various data manipulation tasks.


ForEach {-NoElement -NoNewScope -Parallel} [-FilterScript <String>] [-StopAtEnd] [-Skip} <ScriptBlock>


  • -NoElement: Excludes the current element from the input collection during each iteration.
  • -NoNewScope: Prevents a new scope from being created for each iteration, ensuring variables declared outside the loop remain accessible.
  • -Parallel: Executes the loop in parallel if the collection supports it.
  • -FilterScript : Applies a filter script to each object in the collection, only iterating over objects that satisfy the condition.
  • -StopAtEnd: Stops the loop after iterating over all objects in the collection, preventing subsequent commands from being executed.
  • -Skip: Skips the specified number of objects at the beginning of the collection.


Simple Iteration:

ForEach ($item in $myList) {
    Write-Host "Item: $item"

Parallel Execution:

ForEach -Parallel ($item in $myList) {
    Invoke-Command -ScriptBlock {
        Write-Host "Item: $item" -NoNewLine

Filtering with -FilterScript:

ForEach ($item in $myList) {
    If (($item -like "*.*") -and ($item.Extension -eq "txt")) {
        Write-Host "Text file found: $item"

Common Issues

  • Loop Order: By default, ForEach iterates over collections in the order they are specified. To iterate in reverse order, use the -Reverse operator.
  • Passing Variables by Reference: Variables declared within the ForEach loop are passed by value, which can lead to unexpected results. To modify a variable outside the loop, use the -NoElement option.
  • Infinite Loops: If the ForEach loop modifies the collection it’s iterating over, it can result in an infinite loop. Ensure that modifications to the collection are handled appropriately.


ForEach can be combined with other PowerShell commands for advanced tasks, such as:

  • Where-Object: Filters the collection before iteration using a specified condition.
  • Set-Variable: Assigns values to variables based on each object in the collection.
  • Invoke-Command: Executes a command for each object in the collection in parallel.
  • ForEach-Object: Accepts a pipeline input and iterates over each object in the pipeline.
  • Foreach-Parallel: Executes loops in parallel, supporting custom pipeline input.
  • Invoke-Foreach: Executes a script block for each object in a specified collection, providing additional control over concurrency and error handling.