2

The following if statements with -ne and -or operators is not working (Note I did not include the braces). $MyVariable is an integer coming in from a parameter in a function and having the if statement check the value. What I want is if $MyVariable is not equal to 16, 24 or 32 then return with error message otherwise continue. Calling the function as FunctionName 16; in the ps1 script.

Function is defined as follows:

function FunctionName
{
  param([Parameter(Mandatory = $false, Position = 0)]
            [AllowNull()]
            [int]   $MyVariable,
            [Parameter(Mandatory = $false, Position = 1)]
            [bool] $MyVariable2,
            [Parameter(Mandatory = $false, Position = 2)]
            [bool] $MyVariable3);
  if (...
}

What am I doing wrong in the following if statements?

if ($MyVariable -ne 16 -or $MyVariable -ne 24 -or $MyVariable -ne 32)...
if (16 -ne $MyVariable -or 24 -ne $MyVariable -or 32 -ne $MyVariable)...
if (($MyVariable -ne 16) -or ($MyVariable -ne 24) -or ($MyVariable -ne 32))...
2
  • 2
    Logic flaw. At least two of the -ne comparisons will always be true. Use -and instead, or -eq for the comparison Commented Dec 29, 2016 at 16:39
  • 1
    Yes. After re-looking at the logic it makes sense. Thank you. Commented Dec 29, 2016 at 16:48

1 Answer 1

3

If any one of the three equality comparisons return $false, the two others must return true (if $x equals 16 it will never equal 24 or 32), and so the statement will always evaluate to $true.

Change -or to -and to test for all 3 cases:

if ($MyVariable -ne 16 -and $MyVariable -ne 24 -and $MyVariable -ne 32){}

or check whether it is equal rather than not:

if ($MyVariable -eq 16 -or $MyVariable -eq 24 -or $MyVariable -eq 32){}

or, use the -contains operator instead:

if (@(16,24,32) -contains $MyVariable){}
Sign up to request clarification or add additional context in comments.

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.