Monthly Archive

Scripting Games 2012 comments: #11–its true

The games are over for another year. The number of entries was huge – 150% increase over last year. Congratulations to the winners and to everyone who took part.

One thing I noticed was the number of scripts that made testing booleans harder than it needed to be.

A boolean can take one of two values – True or False. These are represented in PowerShell by $true and $false respectively

Lets create a couple of variables

PS> $x = $true
PS> $x
True
PS> $y = $false
PS> $y
False

A common test was:

PS> $a = $true
PS> $b = $false

PS> if ($a -eq $true){"Do something"}
Do something

or you might see

PS> if ($b -ne $true){"Do something else"}
Do something else

These work and are perfectly understandable.

They can be made simpler

PS> if ($a){"Do something"}
Do something

we get two ways of testing false using the –not operator and its alias of !

PS> if (-not $b){"Do something else"}
Do something else
PS> if (! $b){"Do something else"}
Do something else

 

Just as a final test to show this really works

PS> if ($b){"Do something"}else{"Do something else"}
Do something else

 

The thing to remember is that on an if statement or anywhere else where a condition is being tested it has to resolve to true or false. In this case the variable (or object property) already carries a boolean value so we can use it directly.

Its not a big saving but will mount up over time – keeps the scripts simpler and therefore keeps the errors down

Leave a Reply