PS_newbie PS_newbie - 3 months ago 23
PowerShell Question

powershell if -OR statement with comparison operators not working as expected

I have the following code snippet and I cannot figure out why the

if
is not working.

The goal is to get some input from the user, and if it is a valid input, carry on. If not, then keep asking until it is a valid entry.

No matter what value I enter on the first question (e.g. wmic), it ALWAYS goes into the
do loop
. When entering, say wmic, on the second pass, it breaks the do as desired. Invalid entries keep me in the loop until I enter a correct entry.

$query_means = read-host 'Enter one of psinfo, powershell or wmic'

if ($query_means -ne "wmic" -OR $query_means -ne "psinfo" -OR $query_means -ne "powershell")
{
do {
$query_means = read-host 'Invalid entry. Enter one of psinfo, powershell or wmic'

}Until ($query_means -eq "wmic" -OR $query_means -eq "psinfo" -OR $query_means -eq "powershell")

}


the
until
comparisons workS just fine, breaking when desired.

Would appreciate some suggestions in this regard

Answer

You are using the wrong operator. Let's say that $query_means is wmic. Then your first condition of if statement is false, however other two conditions are true. Since you are using OR operator, the result is true. Using OR operator you will always have at least 2 conditions that evaluate to true, so the overall result will always be true.

Instead you should be using AND operator, because you want condition to be valid when neither of the strings are in the list you provided.

So change -OR to -AND and your code should be fine:

if ($query_means -ne "wmic" -AND $query_means -ne "psinfo" -AND $query_means -ne "powershell")
Comments