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.

safe
  • 650
  • 4
  • 13
  • 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. – Lieven Keersmaekers Sep 15 '15 at 12:27
  • 3
    I would really like to see how $numbers is populate or the exact contents. – Matt Sep 15 '15 at 12:32
  • http://stackoverflow.com/questions/18877580/powershell-and-the-contains-operator/18877724#18877724 – Kev Sep 15 '15 at 13:12

2 Answers2

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.

mjolinor
  • 66,130
  • 7
  • 114
  • 135
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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263