Skip to content

Shortcut evaluation in boolean expressions

2011/11/23

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
True
PS C:> $f
1

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
False
PS C:> $f
5
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
empty.
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.

Advertisements
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: