Introduction: The switch statement checks for multiple case value against a input variable, once a case matches against the input variable then code block in that particular case is executed. Let’s see various switch statements examples as below.
#Copy, Paste and run below examples in PowerShell to see the output.
#Example - 1 : Simple switch statement
$myValue = 'India'
switch($myValue)
{
'India' {'I Live in ' + $myValue}
'UK' {'I Live in ' + $myValue}
'US' {'I Live in ' + $myValue}
'JAPAN' {'I Live in ' + $myValue}
}
#Example - 2 : Check case sensitivity in switch statement
$myValue = 'UK'
switch -CaseSensitive ($myValue)
{
'India' {'I Live in ' + $myValue}
'UK' {'I Live in ' + $myValue}
'US' {'I Live in ' + $myValue}
'JAPAN' {'I Live in ' + $myValue}
}
#Example - 3 : default case in switch statement
$myValue = 'Canada'
switch ($myValue)
{
'India' {'I Live in ' + $myValue}
'UK' {'I Live in ' + $myValue}
'US' {'I Live in ' + $myValue}
'JAPAN' {'I Live in ' + $myValue}
default {'I don''t have place'}
}
#Exmaple - 4 : using -Wildcard in switch statement.
#Choose any one value of $myValue at a time to see the output.
$myValue = 'Jaipur'
$myValue = 'Ukraine'
$myValue = 'Indonasia'
switch -Wildcard ($myValue)
{
'I*N*' {'I Live in ' + $myValue}
'U*K*' {'I Live in ' + $myValue}
'U*S*' {'I Live in ' + $myValue}
'J*P*' {'I Live in ' + $myValue}
default {'I don''t have place'}
}
#Example - 5 : using -Exact in switch statement
#It performs case insensitivity matching against string conditions
$myValue = 'US'
switch -Exact ($myValue)
{
'US' {'I Live in the ' + $myValue}
'us' {'I Live in the ' + $myValue}
'Us' {'I Live in the ' + $myValue}
'india' {'I Live in ' + $myValue}
}
#Example - 6 : break in switch statement
#As break placed in second case so only first two match cases will get executed
$myValue = 'US'
switch ($myValue)
{
'US' { 'First Case ' + $myValue}
'us' {
'Second Case ' + $myValue
break
}
'Us' {'Third Case ' + $myValue}
'india' {'Forth Case ' + $myValue}
}
Conclusion: This article covers frequently used switch statements from the programming perspective, but switch statement also works well with logical expression, –Regex and –File input parameter. The –Regex parameter matches the case and execute the all the case which follows –Regex pattern, and the –File parameter matches each line inside the input file against a case and execute the matching case code block.
Leave a Reply