PowerShell Loops Foreach


ForEach has two different meanings in PowerShell. One is a keyword and the other is an alias for the ForEach-Object cmdlet. The former is described here.

This example demonstrates printing all items in an array to the console host:

$Names = @('Amy', 'Bob', 'Celine', 'David')

ForEach ($Name in $Names)
    Write-Host "Hi, my name is $Name!"

This example demonstrates capturing the output of a ForEach loop:

$Numbers = ForEach ($Number in 1..20) {
    $Number # Alternatively, Write-Output $Number

Like the last example, this example, instead, demonstrates creating an array prior to storing the loop:

$Numbers = @()
ForEach ($Number in 1..20)
    $Numbers += $Number