PowerShell Loops Foreach

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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
}


Got any PowerShell Question?