14

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

Ben
  • 1,137
  • 9
  • 26
  • 44

5 Answers5

13
$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" }
}
Torai
  • 404
  • 2
  • 5
12

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" }
}
Joey
  • 1,853
  • 11
  • 13
2

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

Jindra
  • 21
  • 2
1

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 
Christopher_G_Lewis
  • 3,685
  • 22
  • 27
-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" }
}
Simon
  • 1
  • 1