0

Scenario

When my variable (called $Numbers) contains 0, 1 and 2, it'll run anything under the first IF statement. If my variable contains 0, 1, 2 and 3, it'll run the other IF statement.

Issue

I can't seem to get this working since it continuously runs the first IF statement (due to still containing 0, 1 and 2) but never skips this if it doesn't contain the number 3.

Brief Code Example

If ($Numbers -contains "*0,*" -and "*1,*" -and "*2,*") {

    Write-Host = "Does not contain 3"

}

Elseif ($Numbers -contains "*0,*" -and "*1,*" -and "*2,*" -and "*3,*") {

    Write-Host "Contains 3"

}

Any guidance is appreciated.

3
  • if $Numbers is a collection, drop the wildcards. If $Numbers is a string, use match io contains. In both cases, as Maarten said, reverse the statement. Commented Sep 15, 2015 at 12:27
  • 3
    I would really like to see how $numbers is populate or the exact contents. Commented Sep 15, 2015 at 12:32
  • stackoverflow.com/questions/18877580/… Commented Sep 15, 2015 at 13:12

2 Answers 2

4

Your test syntax is wrong.

-Contains is going to look for exact matches, not wildcard matches, plus each -and condition must be a standalone test, e.g.

If ($Numbers -contains 0 -and $Numbers -contains 1 -and $Numbers -contains 2)

"1," or "2," by themselves are non-null strings and will always evaluate to $true, absent any kind of comparison operation being applied to them.

Sign up to request clarification or add additional context in comments.

Comments

3

Reverse the if statement, test for 0, 1, 2, 3 first, test for 0, 1, 2 in the Elseif. You should always test for the more specific situation first.

Comments

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.