I’m not questioning the odd/even function, but why is the switch statement operating this way.
My understanding is that the PowerShell switch works on evaluating each item as a condition PowerShell Switch
Switch ()
{
{}
{}
}
and that a condition can be a '“string”|number|variable|{ expression } ’
I guess my issue is that I’m trying to equate the PowerShell switch with a C# or C switch statement and when you use an Expression via {} it behaves differently.
Honestly, you’re not meant to use -or and -and that way. Those operators expect both operands to be either True or False. When confronted with a string or number or other non-Boolean values, there are coercion rules. For example:
0 -or 1
Will be True, because 0 is False and 1 is True.
“A” -or “B”
Will be True, because both “A” and “B” are regarded as True values (basically, any nonzero value is True).
In your final example, bear in mind that unless you break out of the construct, each condition matching True will execute.
“A” -or “B” does not read as “If the value is A or the value is B.” Because you’ve enclosed the expression in {}, it executes as a script block, within which $_ represents the comparable value. If the {block} returns True, the matching expression executes.
{ $_ -eq “A” -or $_ -eq “B” } would read as “If the value is A or the value is B,” because -or is being provided two subexpression, either of which will evaluate to True or False.
And while I know you have the working solution of using the full $_ -eq Value for each -or, I wanted to go ahead and throw some alternatives.
$num = 1
switch -Regex ($num) {
"^(1|3|5|7|9)$" { "Odd"}
"^(2|4|6|8|10)$" { "Even"}
}
switch ($num) {
{$_ -in (1,3,5,7,9)} { "Odd"}
{$_ -in (2,4,6,8,10)} { "Even"}
}
#The ones above work on a predefined list, but this one will work no mater what number you throw at it unless it's a negative number.
switch ($num % 2) {
0 { "Even"}
1 { "Odd"}
}