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: 20A 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
EasyRead a line of test scores and print each one and their total.
- Read a line with the prompt
Scores. The scores are whole numbers separated by single spaces. - Split the line into an array of scores.
- With a
foreachloop, printScore:and each score, and add it to a total. - 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: 245Try it yourself
$line = Read-Host "Scores"
# Split the line, print each score and the total
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in PowerShell Basics
5Project: Password Checker
Project OverviewLength Check