Bird
0
0

Find the error in this PowerShell code:

medium📝 Debug Q7 of 15
PowerShell - Control Flow
Find the error in this PowerShell code:
switch -Regex ($value) {
  '^foo' { 'Starts with foo' }
  'bar$' { 'Ends with bar' }
  default { 'No match' }
}

$value = 'foobar'
AThe regex patterns are invalid
BThe variable $value is assigned after the switch block
CMissing parentheses around $value
DThe switch statement cannot use -Regex
Step-by-Step Solution
Solution:
  1. Step 1: Check variable assignment order

    $value is assigned after the switch block, so switch runs with $value as null or empty.
  2. Step 2: Understand impact on matching

    Since $value is empty during switch, no patterns match and default runs.
  3. Final Answer:

    The variable $value is assigned after the switch block -> Option B
  4. Quick Check:

    Assign variables before switch to avoid empty input [OK]
Quick Trick: Assign variables before switch to avoid empty input [OK]
Common Mistakes:
  • Assuming regex patterns are invalid
  • Thinking parentheses are mandatory around variable
  • Believing -Regex is unsupported

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes