Last Updated on August 7, 2025 by Arnav Sharma
PowerShell’s Switch statement is a powerful tool for controlling the flow of a script through pattern matching and condition checking. It allows you to compare a value against a set of predefined patterns or conditions and execute code blocks based on which pattern matches. Here’s a detailed explanation with examples:
Example 1: Basic Syntax:
switch (expression)
{
pattern1 { commands }
pattern2 { commands }
...
default { commands }
}
expression: The value or expression that you want to compare.pattern: The specific value or condition you’re checking against the expression.commands: The code that executes if the pattern matches the expression.default: (Optional) Executes if none of the patterns match.
Example 2: Simple Example:
$color = 'Red'
switch ($color)
{
'Red' { 'Stop' }
'Yellow' { 'Caution' }
'Green' { 'Go' }
default { 'Unknown Color' }
}
This script will output 'Stop' since $color is 'Red'.
Example 3: Using Script Blocks in Patterns:
You can use script blocks for more complex comparisons:
$number = 15
switch ($number)
{
{ $_ -gt 10 } { 'Greater than 10' }
{ $_ -lt 10 } { 'Less than 10' }
default { 'Exactly 10' }
}
This will output 'Greater than 10'.
Example 4: Multiple Values in a Single Case:
You can match multiple values in a single case:
$day = 'Sunday'
switch ($day)
{
'Saturday', 'Sunday' { 'Weekend' }
default { 'Weekday' }
}
This will output 'Weekend'.
Example 5: Using Wildcards:
PowerShell switch supports wildcard characters for pattern matching:
$file = 'document.txt'
switch -Wildcard ($file)
{
'*.txt' { 'Text File' }
'*.jpg', '*.png' { 'Image File' }
default { 'Unknown File Type' }
}
This will output 'Text File'.
Example 6: Using Regular Expressions:
For more complex pattern matching, you can use regular expressions:
$email = '[email protected]'
switch -Regex ($email)
{
'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$' { 'Valid Email' }
default { 'Invalid Email' }
}
This will output 'Valid Email'.