Challenge - 5 Problems
PowerShell ForEach Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate2:00remaining
Output of a ForEach loop with array modification
What is the output of this PowerShell script?
PowerShell
$arr = 1,2,3,4 foreach ($i in $arr) { $i = $i * 2 Write-Output $i } Write-Output $arr
Attempts:
2 left
💡 Hint
Remember that modifying the loop variable inside a ForEach does not change the original array elements.
✗ Incorrect
The loop variable $i is a copy of each element, so changing $i does not affect the original array $arr. The Write-Output inside the loop prints doubled values, but the original array remains unchanged.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in this ForEach loop
Which option contains a syntax error in the ForEach loop?
PowerShell
foreach ($item in $list) {
Write-Output $item
}Attempts:
2 left
💡 Hint
Check the parentheses around the loop variable.
✗ Incorrect
Option A is missing parentheses around the loop variable and collection, which is required syntax in PowerShell ForEach loops.
🔧 Debug
advanced2:00remaining
Why does this ForEach loop not output anything?
Given this script, why is there no output?
PowerShell
$numbers = 1..5 foreach ($num in $numbers) { $num * 2 }
Attempts:
2 left
💡 Hint
In PowerShell, expressions inside loops need to be output explicitly to display.
✗ Incorrect
The expression $num * 2 calculates the value but does not output it. You need to use Write-Output or just place the expression alone to output it.
🚀 Application
advanced2:30remaining
Using ForEach to modify a list of objects
You have a list of objects with a property 'Name'. You want to append '-done' to each Name. Which script correctly updates the objects?
PowerShell
$items = @(
[PSCustomObject]@{Name='Task1'},
[PSCustomObject]@{Name='Task2'}
)
foreach ($item in $items) {
# update Name here
}Attempts:
2 left
💡 Hint
Remember to assign the new string back to the property.
✗ Incorrect
Option A correctly concatenates the string and assigns it back to the Name property. Option A uses += which works but is less clear. Option A replaces the whole object with a string, losing the object structure. Option A uses an invalid operator '-' for strings.
🧠 Conceptual
expert3:00remaining
Understanding pipeline ForEach-Object vs ForEach loop
Which statement about PowerShell's ForEach-Object cmdlet and ForEach loop is TRUE?
Attempts:
2 left
💡 Hint
Think about how pipeline processing works in PowerShell.
✗ Incorrect
ForEach-Object processes each item as it passes through the pipeline, allowing streaming processing. ForEach loop requires the entire collection before starting the loop.