Powershell Switch statement with multiple values
$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" }
}
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" }
}
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
switch ($myNumber) {
{$_ -in 1, 3, 5, 7, 9} { write-host "Odd" }
{$_ -in 2, 4, 6, 8, 10} {write-host "Even" }
}