If statements have been an essential part of programming for about as long as programming has existed. And PowerShell is no different. If statements are a crucial component of PowerShell that help you accomplish things with your PowerShell scripts that otherwise wouldn’t be possible.
Ready to learn about PowerShell if statements? Great! Grab your energizing drink of choice, hang your do not disturb sign on your office door, grab a Snickers Ice Cream Bar (because why not), and join me as we learn all about one of my favorite PowerShell constructs, if statements.
What is an if statement?
An if statement is a programming construct used to add conditional logic to a program or script. Conditional logic allows a script to execute certain actions depending on the evaluation of a predefined condition. Since we’re focusing on PowerShell, I’ll mainly refer to scripts when talking about this topic.
What does that mean in normal lingo? Here’s a super fancy diagram to help us break it down.
When a script encounters an if statement, a condition is evaluated to see if it’s true or false. In this diagram, if the condition evaluates to true, then the script runs a specific command that’s nested in the if statement. If the condition evaluates to false, the script ignores everything contained in the if statement and moves onto the next command.
If statements are powerful because they mimic the decision-making process people use every day. If a condition is met, then something happens. For example, if I’m hungry, then I’ll eat. If I’m cold, then I’ll put on a hoodie. If I’m tired, then I’ll take a nap. Now that I think about it, a nap sounds nice right about now. Must. Soldier. On …
Now let’s look at an example of how an if statement works in PowerShell.
$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 (-lt) 12, display a message. Since $eggs has a value of 10, the condition 10 is less than 12 is true, so the message "You have less than a dozen eggs" is displayed. If we had 13 eggs instead, the condition 13 is less than 12 would have been false and the script would have ignored the message.
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. The condition is just some expression to be evaluated. 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 eggcellent example, I used the -lt comparison operation in my conditional statement, which stands for less than. Here is a list of some of the more common comparison operators you can use in PowerShell.
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, the condition evaluates to true, and 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 condition evaluates to false and the script just ends. 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.
Easily run PowerShell scripts on remote devices
Need to run your awesome PowerShell scripts on remote devices? PDQ Connect can easily execute PowerShell scripts on any managed device with an active internet connection.
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 $xto 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."
Nested if statements in PowerShell
It’s possible, and common, to nest if statements in PowerShell (incoming Inception vibes). Nested if statements allow you to increase the complexity and possible outcomes of your if statements.
To nest an if statement, just embed a new if statement inside the script block of an if or else statement. For example:
$directoryPath = "C:\Files"
$file = "PC_Info.csv"
$fullPath = Join-Path $directoryPath $file
if (Test-Path -Path $directoryPath){
if (Test-Path -Path $fullPath){
"File exists"
}
else {
"File doesn't exist"
}
}
else {
"Directory doesn't exist"
}
This example script checks to see if a directory exists. If the directory exists, it checks to see if a particular file exists.
PowerShell elseif statements
Another way to extend the functionality of your if statements in PowerShell is to use the elseif to evaluate multiple conditions and return multiple outcomes. Sometimes this method can be used to achieve the same result of a nested if statement, but not always.
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 instead of the original two. One outcome 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 returns the else statement, displaying the message "You have more than a dozen eggs."
Combining multiple condition expressions using -and and -or
You can combine multiple condition expressions in your PowerShell if statements using -and and -or.
The -and operator should be used when you want multiple conditions expressions to evaluate to true.
if ((get-process chrome -ErrorAction SilentlyContinue) -and (get-process firefox -ErrorAction SilentlyContinue)){
"Chrome and Firefox are running"
}
else {
"Both Chrome and Firefox are not running"
}
In the example above, both Chrome and Firefox must be running for the condition to return true.
If you want your condition statement to return true as long as one of the expressions returns true, use the -or operator.
if ((get-process chrome -ErrorAction SilentlyContinue) -or (get-process firefox -ErrorAction SilentlyContinue)){
"Chrome or Firefox are running"
}
else {
"Neither Chrome or Firefox are running"
}
In this example, we used the -or operator. The condition returns true as long as Chrome or Firefox is currently running.
Negating PowerShell if 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.”}
PowerShell dinner menu
It’s time to put all this PowerShell if statement knowledge to good use. Let’s use several of the principles we covered in this article to create a script that gives us our dinner plans depending on what day of the week it is.
First, let’s 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"
}
Since I ran this command on a Monday, the returned dinner plan was "Macaroni Monday."
While this script runs as planned and returns the correct results, I need to add a caveat. If you are using several elseif statements in the same command, you may want to consider using a switch statement instead. Switch statements can accomplish the same thing as multiple elseif statements, but are much easier to read, and readability is a big factor when making a PowerShell scripts. If only we had an article that covered switch statements … Oh wait, we do!