ForEach (loop statement)

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

Syntax
      ForEach (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.  

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.

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:

$foreach variable - Refers to the enumerator in a foreach loop.
Break statement
Continue statement
ForEach-Object - Loop for each object in the pipeline (foreach)
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 SS64.com 1999-2014
Some rights reserved