How to use If statements in PowerShell

Brock Bingham candid headshot
Brock Bingham|Updated August 9, 2023
How to use If statements in PowerShell
How to use If statements in PowerShell

If statements are conditional logic statements that you can add to your PowerShell scripts. If statements mimic the decision-making process people use every day. If a condition is met, then something happens. For example, if it's raining outside, I'll grab an umbrella before heading outside.

If statements in PowerShell function similarly to If statements in other programming languages.

powershell if statements 1

In this diagram, if the condition is true, then it runs a specific command or statement. If the condition is false, it moves onto the next command or statement. Here's a simple PowerShell example.

$eggs = 10 if ($eggs -lt 12) { "You have less than a dozen eggs." }
Example of PowerShell If statement.

In this example, we created a variable called $eggs and gave it a value of 10. Next, we set a conditional statement that says if $eggs is less than 12, display a message. Since $eggs has a value of 10, the message "You have less than a dozen eggs" is displayed.

Now that we have a basic understanding of If statements, let's dive a little deeper and go over the syntax and some more advanced examples.

PowerShell If statement syntax

The syntax of If statements in PowerShell is pretty basic and resembles other coding languages.

if (condition) {statement or command}

We start by declaring our If statement followed by the condition wrapped in parentheses. Next, we add the statement or command we want to run if the condition is true and wrap it in curly brackets.

The condition statement itself can be structured in various different ways. Many condition statements use comparison operators. In my earlier eggcelent example, I used the -lt comparison operation in my conditional statement, which stands for less than. Here is a list of some of the comparison operators you can use in PowerShell.

-nenot equals
-gtgreater than
-gegreater than or equal
-ltless than
-leless than or equal
-likestring matches wildcard pattern
-notlikestring does not match wildcard pattern
-matchstring matches regex pattern
-notmatchstring does not match regex pattern
-containscollection contains a value
-notcontainscollection does not contain a value
-invalue is in a collection
-notinvalue is not in a collection
-isboth objects are the same type
-isnotthe objects are not the same type
-notnegates the statement
!negates the statement

Keep in mind that condition statements don't require comparison operators. You can use regular PowerShell cmdlets in the condition statement. For example:

if (Test-Path 'c:\temp\macgyver_biography.txt') { Get-Content 'c:\temp\macgyver_biography.txt' | Measure-Object -Word }
PowerShell example of calling the Test-Path cmdlet to see if a file exists or not.

In this example, we are calling the Test-Path cmdlet to see if a file exists or not. If the file exists, we use the Get-Content and Measure-Object cmdlets to return a word count of the file. If the file does not exist, then the script will just end. As you can see from the screenshot, my MacGyver biography is only 8 words long so far. One of these days, I'll finish it.

PowerShell If-Else statements

Up to this point, we've only talked about If statements. However, you'll often find If statements accompanied by an Else statement. Else statements allow you to perform an additional action if the condition is not met or returns false.

powershell if statements 4

In this diagram, you can see that we now have two statements that can be executed. One statement if the condition returns true, and one statement if the condition returns false. Here's a simple PowerShell If-Else statement example.

$x = 4 if ($x -ge 3) { "$x is greater than or equal to 3" } else { "$x is less than 3" }
Example of PowerShell If-Else statement.

In this example, we've set the variable $x to a value of 4. We then set our If statement with the condition that if $x is greater than or equal to 3, display the message "$x is greater than or equal to 3." Lastly, we set our Else statement that if the condition is false, display the message "$x is less than 3."

You can see from the screenshot that since $x equaled 4, the condition returned true. Now let's change the value of $x to 1, making the condition return false.

$x = 1 if ($x -ge 3) { "$x is greater than or equal to 3" } else { "$x is less than 3" }
Example of false PowerShell If-Else statement.

Now that the condition returns false, you can see that PowerShell is returning our Else statement, "$x is less than 3."

Nesting conditional statements

PowerShell allows you to nest If and Else statements within If and Else statements (incoming Inception vibes). Nested conditional statements basically cycle through the statement until either a statement is returned true or until all statements are returned false. There are a couple of different ways to nest conditional statements. One way is to literally add a new If-Else statement inside an If or Else script block. For example.

if (condition1) { "condition1 is true" } else { if (condition 2) { "condition 2 is true" } else { "condition 2 is false" } }

The second and preferred way to nest conditional statements is to use the elseif statement. Here's an example that builds on the egg example we covered earlier.

$eggs = 14 if ($eggs -eq 12) { "You have exactly a dozen eggs." } elseif ($eggs -lt 12) { "You have less than a dozen eggs." } else { "You have more than a dozen eggs." }
Example of nested conditional statements in PowerShell.

In this example, we have three possible outcomes. One if we have exactly 12 eggs. One if we have less than 12 eggs. And one if we have more than 12 eggs. In the screenshot above, we have our $egg variable set to 14, which returned the Else statement, displaying the message "You have more than a dozen eggs."

Negating PowerShell statements

Sometimes with operators, we need to negate the statement. Using the previous MacGyver example, what if instead of searching for the MacGyver biography, we want to make sure it isn't there? Here's an example of how to do that:

if (!(Test-Path 'c:\temp\macgyver_biography.txt')) {“This Machine lacks the biography you need, perhaps you can create on with a paperclip and a matchstick.”}
Example of how to negate a PowerShell statement.

PowerShell dinner menu

Now that we know all about If statements, Else statements, and nested conditional statements, let's bring it all together by creating a script that will give us our dinner plans depending on what day of the week it is.

First, we'll get the day of the week using the Get-Date cmdlet, returning the DayOfWeek property and assigning it to the $day variable.

$day = (Get-Date).DayOfWeek

Next, we'll build our nested conditional statement for the different days of the week and assign a different meal for each day.

if ($day -eq 'Monday') { "Macaroni Monday" } elseif ($day -eq 'Tuesday') { "Taco Tuesday" } elseif ($day -eq 'Wednesday') { "Waffle Wednesday" } elseif ($day -eq 'Thursday') { "Tilapia Thursday" } elseif ($day -eq 'Friday') { "Falafel Friday" } elseif ($day -eq 'Saturday') { "Sushi Saturday" } else { "Schnitzel Sunday" }
Example of PowerShell script using If statements, Else statements, and nested conditional statements.

Since I ran this command on a Thursday, the returned dinner plan was "Tilapia Thursday." While this script runs as planned and returns the correct results, I need to add a caveat. If you are nesting multiple conditional statements together, you should be using the Switch statement instead. The Switch statement will usually run faster and look cleaner, making it easier to understand compared to multiple nested If-Else statements. If you want to learn more about the Switch statement, stay tuned as we'll cover it more in-depth in a future article.

Wrapping up

PowerShell is an extremely powerful tool that every sysadmin should be using. It becomes even more powerful when you start taking advantage of If-Else statements, allowing you to automate complex tasks based and conditional decision making. Be sure to check out how PowerShell can also help you secure your passwords and schedule tasks.

If you're interested in other powerful tools, make sure you download a free trial of PDQ Deploy and PDQ Inventory. PDQ Deploy will help you keep your network environment up to date, making deployments and updates a breeze. PDQ Inventory will ensure you have all the information you need to properly manage all of your Windows devices. PDQ Inventory also gives you access to the PowerShell scanner, letting you take advantage of all the cool PowerShell knowledge you just learned in this article.

Brock Bingham candid headshot
Brock Bingham

Born in the '80s and raised by his NES, Brock quickly fell in love with everything tech. With over 15 years of IT experience, Brock now enjoys the life of luxury as a renowned tech blogger and receiver of many Dundie Awards. In his free time, Brock enjoys adventuring with his wife, kids, and dogs, while dreaming of retirement.

Related articles