11

Anyone know how I can have a switch statement with multiple possible values like the example below?

switch ($myNumber) {
   1 3 5 7 9 { write-host "Odd" }
   2 4 6 8 10 {write-host "Even" }
}

Used to be easy in VBScript, so I'm sure i'm just missing something simple.

e.g in VBScript

Select Case myNumber 
   Case 1,3,5,7,9
      MsgBox "Odd"
   Case 2,4,6,8,10
      MsgBox "Even"
End Select

Cheers in advance,

Ben

11
$myNumber = 3
$arrA = 1, 3, 5, 7, 9
$arrB = 2, 4, 6, 8, 10
switch ($myNumber) { 
    {$arrA -contains $_} { write-host "Odd" } 
    {$arrB -contains $_} { write-host "Even" }
}
  • +1 Using -eq instead of -contains is even better. – Bernie White Aug 8 '12 at 3:26
11

In your case you can simply use

switch ($myNumber) {
  { $_ % 2 -eq 1 } { "Odd" }
  { $_ % 2 -eq 0 } { "Even" }
}

An actual attempt to model what you can do there in VB would probably be something like

switch ($myNumber) {
  { 1,3,5,7,9  -contains $_ } { "Odd" }
  { 2,4,6,8,10 -contains $_ } { "Even" }
}
  • I like this one better because it's more familiar to traditional switch statements. – Mark Henderson Apr 13 '12 at 8:49
0

Adding this for completeness...

The closest PowerShell code to the above VB script is:

PS C:\> switch (1) {  
  {$_ -eq 1 -or $_ -eq 3 -or $_ -eq 5 -or $_ -eq 7 -or $_ -eq 9} { "Odd"}
  {$_ -eq 2 -or $_ -eq 4 -or $_ -eq 6 -or $_ -eq 8 -or $_ -eq 10} { "Even"}
}
Odd

PS C:\VSProjects\Virtus\App_VM> switch (2) {  
  {$_ -eq 1 -or $_ -eq 3 -or $_ -eq 5 -or $_ -eq 7 -or $_ -eq 9} { "Odd"}
  {$_ -eq 2 -or $_ -eq 4 -or $_ -eq 6 -or $_ -eq 8 -or $_ -eq 10} { "Even"}
}
Even

Because the VB script Select Case operates via an OR

Select Case testexpression
   [Case expressionlist-n
      [statements-n]] . . .
   [Case Else
      [elsestatements-n]]
End Select

"If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause..." Select Case Statement

The interesting thing that I have not been able to figure out is this result:

PS C:\> switch (1) {  
  {1 -or 3 -or 5 -or 7 -or 9} { "Odd"}
  {2 -or 4 -or 6 -or 8 -or 10} { "Even"}
}
Odd
Even 
0

switch ($myNumber) {
{$_ -in 1, 3, 5, 7, 9} { write-host "Odd" }
{$_ -in 2, 4, 6, 8, 10} {write-host "Even" }
}

-1

How about this for an easy alternative using regex?

switch -regex ($myNumber)
{
   "^[13579]$"     { Write-Host "Odd" }
   "^([2468]|10)$" { Write-Host "Even" }
   default         { Write-Host "Other" }
}
  • 1
    -1 for the |10 part. – Deer Hunter Jan 9 '15 at 0:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.