Skip to main content
PDQ.com mobilePDQ.com desktop
Support
Try Now

How to Use If Statements in PowerShell

Brock BinghamBrock Bingham
·

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.

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."
}

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.

OperatorComparison
-eqequals
-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 vlaue
-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

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
}

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 13 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.

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"
}

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"
}

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 is 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."
}

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."

PowerShell Dinner Menu

Now that we know all about If statements, Else statements, and nested conditional statements, let 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') {
	"Talapia Thursday"
}
elseif ($day -eq 'Friday') {
	"Falafel Friday"
}
elseif ($day -eq 'Saturday') {
	"Sushi Saturday"
}
else {
	"Schnitzel Sunday"
}

Since I ran this command on a Thursday, the returned dinner plan was "Talapia 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.

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.

Ready to put the PowerShell Scanner through its paces?

Take our 14-day Free Trial. Feel the power of the PowerShell scanner.
Start a Trial

Don't miss the next post!

8 ways to protect your business from ransomware

Ransomware attacks are on the rise, and it's only a matter of time before your business becomes a target. Learn how to protect yourself before it's too late.

General
PDQ.com
© 2021 PDQ.com Corporation
Products
  • PDQ Deploy ®
  • PDQ Inventory ®
  • SimpleMDM
  • Pricing
  • Downloads
  • Licensing
  • Buy