0
0
PowerShellscripting~10 mins

ForEach loop in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - ForEach loop
Start with collection
Pick next item
Execute loop body with item
More items?
NoExit loop
Back to Pick next item
The ForEach loop picks each item from a collection one by one, runs the loop body using that item, and repeats until all items are processed.
Execution Sample
PowerShell
foreach ($item in 1..3) {
  Write-Output "Item: $item"
}
This loop prints each number from 1 to 3 on its own line.
Execution Table
IterationVariable $itemConditionActionOutput
111 in collection? YesPrint 'Item: 1'Item: 1
222 in collection? YesPrint 'Item: 2'Item: 2
333 in collection? YesPrint 'Item: 3'Item: 3
4N/ANo more itemsExit loop
💡 All items processed, no more items in collection
Variable Tracker
VariableStartAfter 1After 2After 3Final
$itemundefined1233
Key Moments - 2 Insights
What is the value of $item after the loop ends?
After the loop finishes (see execution_table row 4), $item retains the last value (3) because the loop variable persists in the current scope.
Does the loop run if the collection is empty?
No, the loop checks for items before running. If the collection is empty, it exits immediately (like row 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $item during iteration 2?
A1
B2
C3
Dundefined
💡 Hint
Check the 'Variable $item' column at iteration 2 in the execution_table.
At which iteration does the loop stop running?
AAfter iteration 2
BAfter iteration 4
CAfter iteration 3
DIt never stops
💡 Hint
Look at the exit_note and the last row in execution_table.
If the collection was empty, how would the execution_table change?
AIt would have only one row showing exit immediately
BIt would have multiple rows with $item values
CIt would print items anyway
DIt would cause an error
💡 Hint
Refer to key_moments about empty collections and execution_table exit behavior.
Concept Snapshot
ForEach loop syntax:
foreach ($item in collection) {
  # code using $item
}

It runs the code block once for each item in the collection.
When no items remain, the loop ends.
$item holds the current item during each iteration.
Full Transcript
The ForEach loop in PowerShell takes each item from a list or collection one by one. For each item, it runs the code inside the loop using that item. When all items are done, the loop stops. In the example, numbers 1 to 3 are printed one by one. The variable $item changes each time to the current number. After the loop ends, $item retains the last value (3). If the collection is empty, the loop does not run at all.