0
0
PowerShellscripting~5 mins

Switch statement in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a switch statement in PowerShell?
A switch statement lets you test a value against multiple conditions. It runs the code block for the first matching case. It's like choosing a path based on different options.
Click to reveal answer
beginner
How do you write a basic switch statement in PowerShell?
Use the keyword switch followed by parentheses with the value to check. Inside curly braces, list cases with their code blocks. Example:<br>
switch ($value) {
  'a' { Write-Output 'Got a' }
  'b' { Write-Output 'Got b' }
}
Click to reveal answer
beginner
What happens if no case matches in a PowerShell switch statement?
If no case matches, the switch statement does nothing and moves on. You can add a default case to handle unmatched values.
Click to reveal answer
intermediate
Can a PowerShell switch statement handle multiple matches?
Yes! PowerShell switch can process multiple matches if you use the -Regex or -File options. By default, it stops after the first match.
Click to reveal answer
beginner
How do you add a default case in a PowerShell switch statement?
Use the keyword default inside the switch block. It runs if no other case matches. Example:<br>
switch ($value) {
  'a' { Write-Output 'Got a' }
  default { Write-Output 'No match found' }
}
Click to reveal answer
What keyword starts a switch statement in PowerShell?
Aswitch
Bcase
Cselect
Dif
What happens if no case matches and there is no default in a PowerShell switch?
AIt throws an error
BIt runs the last case
CIt repeats the switch
DIt does nothing and continues
How do you write a default case in a PowerShell switch?
Aelse { }
Bdefault { }
Ccase default { }
Dotherwise { }
Which option allows a PowerShell switch to match multiple cases?
A-All
B-Multiple
C-Regex
D-MatchAll
What is the correct syntax to check a variable $color for 'red' or 'blue' using switch?
Aswitch ($color) { 'red' { } 'blue' { } }
Bswitch $color { 'red' { } 'blue' { } }
Cswitch ($color) then { 'red' { } 'blue' { } }
Dswitch { $color == 'red' { } $color == 'blue' { } }
Explain how a switch statement works in PowerShell and when you might use it.
Think about choosing actions based on different options.
You got /4 concepts.
    Write a simple PowerShell switch statement that prints 'Yes' if input is 'y', 'No' if 'n', and 'Unknown' otherwise.
    Use default to catch all other inputs.
    You got /4 concepts.