Repeat the useful part
Use a loop to calculate a running total.
Work through a collection
A foreach statement assigns each item to a variable and runs a block:
foreach ($name in @('WEB-01', 'DB-01')) {
"Checking $name"
}
A for loop is useful when you need an index or counter. Its three parts initialise the counter, test a condition, and update the counter.
for ($i = 0; $i -lt 3; $i++) {
$i
}
Keep a running total
+= adds a value to a variable. Initialise the total before the loop, then output it after the loop finishes.
$total = 0
foreach ($number in 1..3) {
$total += $number
}
$total
1..3 produces the range 1, 2, 3. ForEach-Object is another way to process each item, specifically in a pipeline. Although the names are similar, it is a cmdlet rather than the foreach language statement.
Use Stop if you accidentally write a loop that never ends. The lab also limits each execution to 30 seconds.
foreach ($name in @('WEB-01', 'DB-01')) {
"Checking $name"
}Put it into practice.
Add the numbers 1 through 5 and output one total after the loop finishes.
See an explained solution
$total = 0
foreach ($number in 1..5) {
$total += $number
}
$totalThe loop accumulates 1+2+3+4+5. Outputting only after the loop produces one result, 15.