PowerShell ForEach Loop: Examples, 1..10 Ranges and Traps

A PowerShell foreach loop repeats a block of code once for each item in a collection: an array, a folder of files, command output, or a number range such as 1..10. The current item lands in the variable you name before in:

foreach ($item in $collection) {
    # do something with $item
}

Here’s a real one that walks through an array of office names:

$cities = 'Seattle', 'Denver', 'Austin', 'Boston'

foreach ($city in $cities) {
    "Checking the $city office"
}

Output:

Checking the Seattle office
Checking the Denver office
Checking the Austin office
Checking the Boston office
PowerShell foreach loop through an array of office names
A foreach loop over an array (PowerShell 7)

In this tutorial, I’ll show you how the PowerShell foreach loop handles arrays, 1..10 number ranges, letter ranges, files and hashtables, plus break, continue and the traps that stop scripts.

I ran every snippet in PowerShell 7.6 and Windows PowerShell 5.1. Where the two disagree, you’ll see both outputs.

Loop through an array with foreach

Arrays are the most common use. You don’t need an index or a counter, and the loop stops on its own after the last item.

This one adds up a list of order amounts:

$orders = 120.50, 89.99, 240.00, 15.25
$total = 0

foreach ($amount in $orders) {
    $total += $amount
}

"Orders: $($orders.Count)  Total: {0:C}" -f $total

Output:

Orders: 4  Total: $465.74

The {0:C} format shows the total as currency, which is dollars with two decimals on a US system.

If you’d rather collect results than add them up, see how to add items to an array in PowerShell.

How do I loop from 1 to 10 in PowerShell?

Use the range operator, two dots between a start and an end number. 1..10 builds the numbers 1 through 10, and foreach walks them:

foreach ($n in 1..10) {
    'Checking SRV{0:D2}' -f $n
}

Output:

Checking SRV01
Checking SRV02
Checking SRV03
Checking SRV04
Checking SRV05
Checking SRV06
Checking SRV07
Checking SRV08
Checking SRV09
Checking SRV10