Multiple Values in a PowerShell Switch Statement

I’ve needed to use multiple values in a PowerShell Switch statement a number of times recently and can never quite remember the syntax, so thought it would be useful to get it down on paper so to speak.

In PowerShell you can use a switch statement instead of using multiple if statements, e.g.

$a = 3 switch ($a) { 1 {"It is one."} 2 {"It is two."} 3 {"It is three."} 4 {"It is four."} }

However, what if you want to test matching the number 3 and the word 3? You could do this, which would be a bit rubbish:

$a = "three" switch ($a) { 1 {"It is one."} 2 {"It is two."} 3 {"It is three."} "three" {"It is three."} 4 {"It is four."} }

Much better though is this:

$a = "three" switch ($a) { 1 {"It is one."} 2 {"It is two."} {($\_ -eq 3) -or ($\_ -eq "three")} {"It is three."} 4 {"It is four."} }

You are able to do this because the syntax for using the switch statement is the below, the key part being:

“string”|number|variable|{ expression }

    switch \[-regex|-wildcard|-exact\]\[-casesensitive\] ( pipeline )

or

    switch \[-regex|-wildcard|-exact\]\[-casesensitive\] -file filename

followed by

    {
        "string"|number|variable|{ expression } { statementlist }
        default { statementlist }
    }