Skip to content

No precendence of logical compare operators in Powershell

2012/04/06

One of my scripts produced unexpected results. I used a condition

if (  $a  -or $b -and $c) ….

example:   if  (I’m swimming OR it is raining AND I am outside ) { I’m wet}

I assumes that the -and has higher precedence and the condition  would be true when

either B AND C are true       Im outside    plus    it is raining at the same time

or  A is true                                I’m swimming

That was what I learned in other programming languages where and-conditions are evaluated first (that what I remember on boolean logic).

But look a the logic table:

($false,$true) | %{
      $A = $_;
     ($false,$true)| %{
         $B = $_;
            ($false,$true)| %{
                 $C = $_;
                 "$A -or $B -and $C is $($A -or $B -and $C)"
         }}}
False -or False -and False is False
False -or False -and True  is False
False -or True  -and False is False
False -or True  -and True  is True
True -or False -and False is False <-- should be true (not wet although I'm swimming)
True  -or False -and True  is True
True -or True -and False is False <-- should be true (not wet although swimming)
True  -or True  -and True  is True

The marked rows do not show the expected result.

Thinking boolean,   A or B and C is the same as B and C or A . But look at the different results in Posh

 ($false,$true)| %{ $A = $_; ($false,$true)| %{$B = $_; ($false,$true)| %{ $C = $_;
      "$B -and $C -or $A is $($B -and $C -or $A)" }}}
False -and False -or False is False
False -and True  -or False is False
True  -and False -or False is False
True  -and True  -or False is True
False -and False -or True is True
False -and True  -or True  is True
True -and False -or True is True
True  -and True  -or True  is True

That is why brackets are needed. the statement that produces the correct result is

Is ( $A -or ($b -and $C)  )

Advertisements

From → basics, powershell

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: