Bird
0
0

What will be the output of this PowerShell code?

medium📝 Command Output Q5 of 15
PowerShell - Control Flow
What will be the output of this PowerShell code?
switch -Regex ('dog', 'cat', 'caterpillar') {
  '^cat' { 'Starts with cat' }
  'dog' { 'Exact dog' }
  default { 'No match' }
}
ANo match Starts with cat Starts with cat
BNo match Exact dog No match
CStarts with cat No match Starts with cat
DNo match No match No match
Step-by-Step Solution
Solution:
  1. Step 1: Evaluate each input against regex patterns

    Input 'dog': matches 'dog' pattern exactly? Yes, but order matters. The first pattern is '^cat' which does not match 'dog'. The second pattern 'dog' matches exactly, so output is 'Exact dog'.
  2. Step 2: Check 'cat'

    'cat' matches '^cat' pattern (starts with 'cat'), so output is 'Starts with cat'.
  3. Step 3: Check 'caterpillar'

    'caterpillar' also starts with 'cat', so matches '^cat' pattern, output 'Starts with cat'.
  4. Step 4: Consider multiple matches

    By default, switch -Regex processes all matching patterns per input. For 'dog', only 'dog' matches. For 'cat' and 'caterpillar', only '^cat' matches.
  5. Final Answer:

    No match Starts with cat Starts with cat -> Option A
  6. Quick Check:

    Regex matches all patterns; order matters [OK]
Quick Trick: Regex matches all patterns; order matters [OK]
Common Mistakes:
  • Assuming only first match is processed
  • Confusing exact match with regex start anchor
  • Ignoring multiple matches per input

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes