What's the PowerShell syntax for multiple values in a switch statement?

Viewed 138732

I basically want to do this:

switch($someString.ToLower())
{
    "y", "yes" { "You entered Yes." }
    default { "You entered No." }
}
9 Answers

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.

Here's another one. Switch is case insensitive anyway. -eq with an array on the left will return the thing it's equal to, and anything returned is true.

switch($someString)
{
  { 'y', 'yes' -eq $_ } { 'You entered Yes.' }
  default               { 'You entered No.'  }
}

The switch doesn't appear to be case sensitive in PowerShell 5.1. All four of the $someString examples below work. [Fixed, thanks js2010]

$someString = "YES"
$someString = "yes"
$someString = "yEs"
$someString = "y"
$someString = "n"

switch ($someString) {
   {"y","yes" -eq $_} { "You entered Yes." }
   Default { "You didn't enter Yes."}
}
Related