ForEach (loop statement)

Loop through a set of input objects and perform an operation (execute a block of statements) against each.

Syntax
      ForEach [-Parallel] (item In collection) {ScriptBlock}

key
   item         A variable to hold the current item
   collection   A collection of objects e.g. filenames, registry keys, servernames
   ScriptBlock  A block of script to run against each object.
   -Parallel    Run the commands once for each item in parallel (PowerShell Workflow only).

The collection will be evaluated and stored as an array in memory before the scriptblock is executed.

The foreach statement does not use pipelining (unlike ForEach-Object ) If you use foreach in a command pipeline PowerShell will actually run the foreach alias that calls ForEach-Object.

Use the ForEach statement when the collection of objects is small enough that it can be loaded into memory.
Use the ForEach-Object cmdlet when you want to pass only one object at a time through the pipeline, minimising memory usage. In most cases ForEach will run faster than ForEach-Object, there are exceptions, such as starting multiple background jobs. If in doubt test both options with Measure-Command.

ForEach -Parallel is valid only in a PowerShell Workflow, there is currently no general parallel support for the foreach keyword.

In PowerShell 4.0 and later, the ForEach method provides even faster performance.

Examples

Loop through an array of strings:

$trees = @("Alder","Ash","Birch","Cedar","Chestnut","Elm")

foreach ($tree in $trees) {
   "$tree = " + $tree.length
}

Loop through a collection of the numbers, echo each number unless the number is 2:

foreach ($num in 1,2,3,4,5) {
  if ($num -eq 2) { continue } ; $num
}

Loop through a collection of .txt files:

foreach ($file in get-ChildItem *.txt) {
  Echo $file.name
}

“The only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you'll know when you find it” - Steve Jobs

Related PowerShell Cmdlets

$foreach variable - Refers to the enumerator in a foreach loop.
Break statement
Continue statement
ForEach-Object - Loop for each object in the pipeline (foreach).
ForEach (method) - Loop through items in a collection.
For - Loop through items that match a condition.
IF - Conditionally perform a command.
Switch - Multiple if statements.
While - Loop while a condition is True.


 
Copyright © 1999-2024 SS64.com
Some rights reserved