Skip to content

Shortcut evaluation in boolean expressions


Powershell uses shortcut evaluation like C does. This means as soon as a boolean expression can be
definitively evaluated the further processing is stopped.

This can be shown like this:

When $f is equal 1 the right side of the -or is not processed
and $f never gets incremented

PS C:> $f = 1
PS C:> $f -eq 1 -or ($f++) -eq 3
PS C:> $f

if $f has a different value than 1 the increment operation takes places

PS C:> $f=4
PS C:> $f -eq 1 -or ($f++) -eq 3
PS C:> $f
PS C:>

This can be dangerous when you build such expressions and
believe that the second operation always takes place.

Where can this be helpful is in cases like this:

you want to evaluate a string but this string can also be
You want to do something if the string is empty or the string does not start
with “xyz”

if the string variable is $null you cannot call substring function on it without generating an error.

If you use

[string]::isNullorempty($variable) -or  $variable.substring(0,3) -eq “xyz”

The substring expression is not evaluated and no error is thrown.

Leave a Comment

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: