Menu
CoddyTech

Foreach Loops

Part of the PowerShell Basics section of Coddy's PowerShell journey. Lesson 17 of 28.

foreach runs a block once for every item of an array. In each round the loop variable holds the current item:

$prices = @(4, 10, 6)
$sum = 0
foreach ($p in $prices) {
    Write-Output "Item: $p"
    $sum += $p
}
Write-Output "Sum: $sum"
Item: 4
Item: 10
Item: 6
Sum: 20

A running total starts before the loop and is printed after it; code inside the braces runs once per item.

Items split from input are strings. $sum += $p still adds numbers here because $sum started as the number 0, and PowerShell converts the right side to the type of the left. Started as "", the total would join the text into 4106. Convert with [int] to make the intent clear.

challenge icon

Challenge

Easy

Read a line of test scores and print each one and their total.

  1. Read a line with the prompt Scores. The scores are whole numbers separated by single spaces.
  2. Split the line into an array of scores.
  3. With a foreach loop, print Score: and each score, and add it to a total.
  4. After the loop, print Total: and the total.

With the input 85 90 70, your script prints:

Scores: 85 90 70
Score: 85
Score: 90
Score: 70
Total: 245

Try it yourself

$line = Read-Host "Scores"
# Split the line, print each score and the total
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in PowerShell Basics