PowerShell for Windows Admins

May 5 2012   7:55AM GMT

Scripting Games 2012 comments: #11–its true

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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
PS> $y = $false
PS> $y

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

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: