PowerShell if not

When you’re using an if statement you’re usually testing for a positive so how do you do a PowerShell if not

There a few scenarios to cover. The simplest is if you’re testing a boolean:

PS> $x = $true

if ($x) {‘Yes’} else {‘No’}
Yes

In an if statement the test ($x) is evaluated and must give a true or false answer. If true then Yes else No

Let’s make turn the test into a not test. You can use ! or –not as you prefer

PS> $x = $true

if (!$x) {‘Yes’} else {‘No’}
if (-not $x) {‘Yes’} else {‘No’}
No
No

If the value is already false

PS> $x = $false

if (!$x) {‘Yes’} else {‘No’}
if (-not $x) {‘Yes’} else {‘No’}
Yes
Yes

Be careful as you’re getting into double negative territory which is always a headache when you come to review the code at some time in the future.

If you’re dealing with numeric values

PS> $x = 5

if ($x -ne 5) {‘Yes’} else {‘No’}
if ($x -lt 5) {‘Yes’} else {‘No’}
if ($x -gt 5) {‘Yes’} else {‘No’}
No
No
No

Be careful with the first one as you’ll only get Yes if $x –ne 5. Back to double negative thinking.

Notice you can’t do this

if ($x -not -lt 5) {‘Yes’} else {‘No’}

Double operators don’t work. You get an error about

At line:1 char:8
+ if ($x -not -lt 5) {‘Yes’} else {‘No’}
+        ~~~~
Unexpected token ‘-not’ in expression or statement.
At line:1 char:8

among other things.

Nulls can be tricky

PS> $x = $null

if ($x) {‘Yes’} else {‘No’}
if (!$x) {‘Yes’} else {‘No’}

No
Yes

A null value will evaluate as false unless you –not it – another double negative situation.

Using if not is relatively straight forward. Just make sure you have the logic thought through to deal with double negatives correctly.

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

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 )

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 )

w

Connecting to %s