Foreach
suggest changeForEach 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
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents