Introduction
A switch statement helps you choose what to do based on different values. It makes your script easier to read when you have many options.
A switch statement helps you choose what to do based on different values. It makes your script easier to read when you have many options.
switch (<expression>) {
<value1> { <code1> }
<value2> { <code2> }
default { <defaultCode> }
}The switch keyword starts the statement.
Each value is checked against the expression. If it matches, the code inside runs.
$color and prints a message.switch ($color) {
'red' { Write-Output 'Stop' }
'green' { Write-Output 'Go' }
default { Write-Output 'Wait' }
}switch (5) { 1 { 'One' } 5 { 'Five' } default { 'Other' } }
This script checks the day and prints a message for Tuesday.
$day = 'Tuesday' switch ($day) { 'Monday' { Write-Output 'Start of work week' } 'Tuesday' { Write-Output 'Second day' } 'Friday' { Write-Output 'Almost weekend' } default { Write-Output 'Just another day' } }
You can use default to catch any value not listed.
Switch statements can match strings, numbers, or even patterns.
Switch statements help pick actions based on values.
They make code cleaner than many if-else checks.
Use default to handle unexpected cases.
switch statement in PowerShell?switch (3) {
1 { 'One' }
2 { 'Two' }
3 { 'Three' }
default { 'Other' }
}switch $color {
'red' { 'Stop' }
'green' { 'Go' }
default { 'Wait' }
}Pass the test and this pattern moves unknown