PowerShell Foreach Loop
A foreach loop is a loop that runs its block once for each item in a list. It visits every item in order, one at a time.
Double each number
The variable $n holds one number at a time, from 1 to 3.
foreach ($n in 1..3) { $n * 2 }Add the numbers up
The total starts at 0 and grows by one number on each pass.
$total = 0
foreach ($n in 1..4) { $total = $total + $n }
$totalPrint a line per item
The block can print a message that uses the current item.
foreach ($n in 1..3) { "Step $n" }Example
$big = 0
foreach ($n in 1..6) { if ($n -gt 3) { $big = $big + 1 } }
"Numbers above 3: $big"Key points
- Foreach: a loop that runs its block once for each item in a list.
- List: several values in order, such as 1..5.
- Item variable: the variable in parentheses holds one item at a time, and changes on each pass.
- Order: items are visited in the order they appear.
- Use a foreach loop when you need to do the same job for every item.
In this example, $big starts at 0. The loop visits each number from 1 to 6. When a number is greater than 3, $big grows by one. The last line prints how many numbers were above 3.
Note
this foreach statement is not ForEach-Object. ForEach-Object works inside a pipeline, and this statement works on its own.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does this loop print? foreach ($n in 1..3) { $n * 10 }