0
0
PowerShellscripting~5 mins

ForEach loop in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a ForEach loop in PowerShell?
A ForEach loop in PowerShell repeats a block of code for each item in a collection, like going through a list one by one.
Click to reveal answer
beginner
How do you write a basic ForEach loop in PowerShell to print each item in a list?
Use:
foreach ($item in $list) { Write-Output $item }
This runs the code inside the braces for every item in $list.
Click to reveal answer
beginner
What does $item represent inside a ForEach loop?
$item is a variable that holds the current element from the list during each loop cycle.
Click to reveal answer
intermediate
Can you use a ForEach loop to process objects, not just simple values?
Yes! ForEach loops can handle any collection, including objects, letting you access properties of each object inside the loop.
Click to reveal answer
beginner
What happens if the collection in a ForEach loop is empty?
The loop body does not run at all because there are no items to process.
Click to reveal answer
What keyword starts a ForEach loop in PowerShell?
Arepeat
Bfor
Cloop
Dforeach
In the loop foreach ($item in $list) { ... }, what is $list?
AThe current item
BThe collection of items to loop through
CA command
DA function
What will this code output?<br>
$numbers = 1,2,3<br>foreach ($n in $numbers) { Write-Output $n }
A123
BError
C1 2 3 (each on a new line)
DNothing
If the collection is empty, how many times does the ForEach loop run?
AZero times
BOnce
CInfinite times
DDepends on the code
Which of these can you loop over with a ForEach loop in PowerShell?
AAll of the above
BAn array of objects
CA collection of numbers
DA list of strings
Explain how a ForEach loop works in PowerShell and give a simple example.
Think about how you would tell a friend to repeat an action for each item in a list.
You got /4 concepts.
    Describe what happens inside the loop variable during each iteration of a ForEach loop.
    Imagine picking one item at a time from a basket and doing something with it.
    You got /3 concepts.