What's the PowerShell syntax for multiple values in a switch statement?
switch($someString.ToLower())
{
{($_ -eq "y") -or ($_ -eq "yes")} { "You entered Yes." }
default { "You entered No." }
}
I found that this works and seems more readable:
switch($someString)
{
{ @("y", "yes") -contains $_ } { "You entered Yes." }
default { "You entered No." }
}
The "-contains" operator performs a non-case sensitive search, so you don't need to use "ToLower()". If you do want it to be case sensitive, you can use "-ccontains" instead.
You should be able to use a wildcard for your values:
switch -wildcard ($someString.ToLower())
{
"y*" { "You entered Yes." }
default { "You entered No." }
}
Regular expressions are also allowed.
switch -regex ($someString.ToLower())
{
"y(es)?" { "You entered Yes." }
default { "You entered No." }
}
PowerShell switch documentation: Using the Switch Statement
switch($someString.ToLower())
{
"yes" { $_ = "y" }
"y" { "You entered Yes." }
default { "You entered No." }
}
You can arbitrarily branch, cascade, and merge cases in this fashion, as long as the target case is located below/after the case or cases where the $_ variable is respectively reassigned.
n.b. As cute as this behavior is, it seems to reveal that the PowerShell interpreter is not implementing switch/case as efficiently as one might hope or assume. For one, stepping with the ISE debugger suggests that instead of optimized lookup, hashing, or binary branching, each case is tested in turn, like so many if-else statements. (If so, consider putting your most common cases first.) Also, as shown in this answer, PowerShell continues testing cases after having satisfied one. And cruelly enough, there even happens to be a special optimized 'switch' opcode available in .NET CIL which, because of this behavior, PowerShell can't take advantage of.