Bird
0
0

Why does this PowerShell script cause an error?

medium📝 Debug Q7 of 15
PowerShell - Control Flow
Why does this PowerShell script cause an error?
$numbers = 1..3
foreach ($n in $numbers) Write-Output $n Write-Output ($n * 2)
AWrite-Output cannot be used inside loops
BMissing braces around loop body
CRange operator is invalid
DVariable $n is undefined
Step-by-Step Solution
Solution:
  1. Step 1: Analyze loop syntax

    The loop body contains two statements: Write-Output $n and Write-Output ($n * 2), without braces or semicolon.
  2. Step 2: Identify the error

    PowerShell requires braces for multiple statements in a foreach loop body.
  3. Final Answer:

    Missing braces around loop body -> Option B
  4. Quick Check:

    Multiple loop statements require braces [OK]
Quick Trick: Braces required for multi-statement foreach loops [OK]
Common Mistakes:
  • Assuming braces always required
  • Thinking variable is undefined
  • Misunderstanding range operator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes