2

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?

1
  • 1
    Simpler or more obtuse? Commented Oct 12, 2016 at 17:34

1 Answer 1

4

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) {
    # ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

I agree about the regex solution not being good for this. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.