Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 4 down vote accepted
$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" }
}
share|improve this answer
    
Thanks its works...I was looking for it since 2 days –  user117386 Apr 13 '12 at 7:06
    
+1 Using -eq instead of -contains is even better. –  Bernie White Aug 8 '12 at 3:26

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" }
}
share|improve this answer
    
I like this one better because it's more familiar to traditional switch statements. –  Mark Henderson Apr 13 '12 at 8:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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