Search notes:

PowerShell: Foreach Statement

Iterating over an array

foreach can be used to iterate over an array:
$ar = 10 .. 14

foreach ($elem in $ar) {
  $elem / 3
}

# 3.33333333333333
# 3.66666666666667
# 4
# 4.33333333333333
# 4.66666666666667
Github repository about-powershell, path: /language/statement/foreach/array.ps1

Skipping specific elements in an iteration

The continue statement allows to skip specific iterations:
forEach ($val in 'foo', 'bar', 'baz') {

  if ($val -eq 'foo') {
    write-host 'Skip processing of foo'
    continue
  }

  write-host "Processing $($val)"

}
Github repository about-powershell, path: /language/statement/foreach/continue.ps1

Breaking out of a foreach loop

The break statement causes the foreach loop to be immediately terminated.
The following example only prints the square numbers from 1 through 4.
foreach ($num in 1 .. 10) {

  if ($num -eq 5) { break }

  write-host "$($num) * $($num) = $($num * $num)"

}
Github repository about-powershell, path: /language/statement/foreach/break.ps1

Iterating over files in a directory

Because get-childItem retuns an array of objects, it can be easily combined with foreach to iterate over some files in a directory:
foreach ($fileObj in get-childItem '*i*.ps1') {

 #
 # Convert the System.IO.FileInfo object to a string:
 #
   $fileStr = split-path -leaf $fileObj

   write-output $fileStr
}
Github repository about-powershell, path: /language/statement/foreach/get-childItem.ps1
In a similar fashion, foreach can be used on any cmdLet that returns an array of objects.

See also

An object is required to implement the System.Collections.IEnumerator interface in order for foreach to be able to iterate over the object. This example tries to demonstrate how an object can implement this interface.
The forEach-object cmdlet can also be abbreviated with foreach.
The break statement exits a loop.
The for statement.
Other statements

Index