Is there a simpler way to specify an -or condition? For example, if ($returnValue -eq 0 -or $returnValue -eq 5). I would rather write something like if ($returnValue -eq 0 -or 5) to test two possible values of $returnValue. Of course that's doing something else.
Ok, just thought of coercing the value into a character type using a regular expression:
if ($returnValue -match '0|5')
So, now that I've answered my question, any other ideas?
-
1Simpler or more obtuse?Austin T French– Austin T French2016-10-12 17:34:06 +00:00Commented Oct 12, 2016 at 17:34
Add a comment
|
1 Answer
I would use -contains or -in where appropriate:
if ((0,5) -contains $returnValue)
or
if ($returnValue -in (0,5))
-in was added in PowerShell v3.
I highly discourage the regex "solution" because it can have unintended side effects and reduces clarity. For example 51 -match '0|5' is $true.
Consider just formatting your if statement on multiple lines:
if (
$returnValue -eq 0 -or
$returnValue -eq 5
)
Though I still like -contains and -in for what you're trying to achieve.
$validVals = @(
0,
5,
17
)
if ($validVals -contains $returnVal) {
# ...
}
if ($returnVal -in $validVals) {
# ...
}
1 Comment
Roman
I agree about the regex solution not being good for this. Thanks.