Prof. Powershell

Lessons in Logic

Lesson 1: Using an IF construct in a PowerShell script.

If you've done any sort of scripting, you've likely used logic constructs like If..Then..Else. PowerShell can also use these logic constructs and I plan on introducing some of them to you over the next few weeks.

But don't think you need a script to use them. You can use these constructs directly in the console. Let's look today at an IF construct. In PowerShell, this is the minimum syntax:

PS C:\> if (5 -gt 2) {write-host "bigger"}

Notice that there is no THEN and no END IF. The IF keyword evaluates the expression in parentheses and if TRUE, executes whatever commands are enclosed in the curly braces. In this example, the word "bigger" is written to the console.

Also in this example, if the expression evaluated FALSE you wouldn't get anything.

Here's where you can add an ELSE clause:

PS C:\> $x=5
PS C:\> if ($x -gt 2) {write-host "X is bigger"} else {write-host "X is smaller"}
X is bigger

If the expression is TRUE then the first script block is executed, otherwise the second script block is executed. You can also perform secondary comparisons using an ELSEIF clause:

PS C:\> $x=5
PS C:\> if ($x -gt 10) {write-host "X is bigger"} elseif ($x -ge 5) {write-host "X is in the middle"} else {write-host "X is smaller"}
X is in the middle

In this example, I'm evaluating three conditions:

  1. If $x is greater than 10, then the first script block is executed;
  2. Otherwise (elseif), if $x is greater or equal than 5, then execute the second script block.
  3. Finally, if neither of those is true then execute the last script block.

It is important to remember that PowerShell will only execute the script block for the first expression that evaluates True.

PowerShell doesn't really care about the formatting and spacing of all the braces, so you can write it as one line in the console, although in a script you are more likely to write it like this:

if ($x -gt 10)
  write-host "X is bigger"
  elseif ($x -ge 5)
  write-host "X is in the middle"
  write-host "X is smaller"

A format like this makes it easier to understand, especially if you have multiple ElseIf clauses. I encourage you to read the help file on IF in PowerShell.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular