PowerShell for Windows Admins

Feb 23 2018   12:01PM GMT

PowerShell if

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

The PowerShell if statement enables you to branch your code depending in the results of one or more conditional tests. The tests can be anything you need but must produce a boolean – true/false – result. Also 0 is treated as $false and a positive non-zero is $true. A negative non-zero generates an error.

The syntax fro an if statement is

if (<test>){<statement list>}
elseif (<test>){<statement list>}
else {<statement list>}

You can have as many elseif sections as required. Note that the tests and statement lists are independent in each section.

As an example of an if statement in use:

$x = 7

if ($x -gt 9){“`$x more than 9 : $x”}
elseif ($x -gt 6){“`$x more than 6 : $x”}
elseif ($x -gt 3){“`$x more than 3 : $x”}
else {“`$x less than 3 : $x”}

Very often you’ll not be using elseif

$x = 7
if ($x -gt 5){“`$x more than 5 : $x”}
else {“`$x less than 5 : $x”}

If $x = 5 you’ll get a slightly misleading message so may be better to do this

$x = 5
if ($x -ge 5){“`$x more or equal to 5 : $x”}
else {“`$x less than 5 : $x”}

I often see code like this for testing boolean values

$x = $true
if ($x -eq $true){“`$x is true”}
else {“`$x is false”}

You don’t need to explicitly test in this case

$x = $true
if ($x){“`$x is true”}
else {“`$x is false”}

The variable will be true or false so just need the variable

$x = $null
if ($x){“`$x is true”}
else {“`$x is false”}

If a variable is $null then you’ll test false returned.

You should always try to test a positive rather than a negative. So

$x = $true
if ($x){“`$x is true”}
else {“`$x is false”}

rather than

$x = $true
if (-not $x){“`$x is false”}
else {“`$x is true”}

Double or triple or more negatives will make your head explode.

You can also perform multiple tests simultaneously

$x = 7
if (($x -gt 8) -or ($x -eq 7)) {“`$x is high : $x”}
else {“`$x is low : $x”}

$x = 7
if (($x -lt 10) -and ($x -ge 7)) {“`$x is high : $x”}
else {“`$x is low : $x”}

In both cases the result is:

$x is high : 7

You don’t need the () round each test but I find it helps when debugging as the code is more readable.

For the –or scenario EITHER test must evaluate to $true and for the –and scenario BOTH scenarios must evaluate to $true

The else statement is the default if the if and elseif tests all fail.

If you find your self using a number of elseif statements a switch is most likely a better code structure.

 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: