Foreach

suggest change

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
}

This version builds the array inside the loop. $Numbers += $Number copies the array on every iteration, so prefer the previous example, which collects the loop's output:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents