Powershell If Else Explained: Syntax and Examples

-

|

Introduction

PowerShell If Else statement runs a command if a specified condition is met. The Else part of PowerShell If Else loop is used to specify multiple conditions.

This guide covers PowerShell If Else statement, Syntax and examples.

To make the best use of this guide I strongly recommend that a) you read this guide without jumping a section. b) you run the commands in the examples section of the guide.
Advertisements


Syntax of the Powershell If Else Statement

The syntax of the If statement is shown below:

If (Condition is true) 
{Execute the codes here}

The If statement block can also have multiple conditions as shown below:

If (Condition 1 is true) 
{execute the code here}
ElseIf (Condition 2 is true)
{Execute the code here instead}
Else {Execute the code in this block}

Note that the last syntax has If, ElseIf and Else. Later in the guide, I will give you examples of how to use and apply both.

When you run a Powershell If statement, Windows PowerShell evaluates the condition for True or False. If the statement is True, PowerShell executes the code in the “{}” block. However, if the condition is false, PowerShell will exit. The opposite of this statement may be true depending on how the statement is constructed.

Powershell If Else Syntax for “NOT True

You can add a NOT True statement in the condition test portion of the If statement. Here is the Syntax.

If !(Condition is NOT true) 
{Execute the codes here}

The “!” reverses the result in the () bock. For example, if the result was TRUE, “!” turns it to FALSE. More on this in the example section.

The NOT True condition can also include multiple conditions. See the syntax below:

If !((Condition 1 is NOT true)) 
{execute the code here}
ElseIf !(Condition 2 is NOT true)
{Execute the code here instead}
Else {Execute the code in this block}

Powershell Conditional Operators (Or Statements)

I am including this in this guide because PowerShell If statement works with Powershell Conditional Operators. The condition test part of If statement will include one or two conditional statements.

A Conditional statement allows you to compare two values for True or False. There are 5 categories: Equality, Matching, Containment, Replacement and Type.

Some examples of an Equality conditional statement are -eq (equals), -ne (not equals). Matching conditions check whether two values match. Examples are -match, -like, -notlike. For a full list of conditional statements click About Comparison Operators.

I know the whole thing may still be sounding like jargon but I will put it all together. Keep reading.

PowerShell If Else Examples

This section puts it together with examples. The first is a basic example. The second example demonstrates how to use PowerShell If to create a folder if it does not exist. Finally, the third example covers how to use multiple conditions.

PowerShell If Else Example 1: Basic

Before I give any example, lets revisit the Syntax of the If statement.

If (Condition is true) 
{Execute the codes here}

To begin with, lets add a real condition into the () block.

(1 -gt 2)  

This command tells PowerShell to check if “1” is greater than “2” and return True of False.

Copy the command, paste it in PowerShell then press Enter on your keyboard. Here is the result

Powershell If Else Explained: Syntax and Examples

The result is obviously False as seen in the image above.

Next, we will add a value in the {} section of the Syntax. To make it easy, I will just add a simple PowerShell command to the block.

{Get-Command} 

Get-Command cmdlet returns a list of all PowerShell cmdlets in your computer. To read more about Get-Command, click PowerShell Get-Command: Syntax, Applications, Examples.

In the final part of this first example, lets combine all the various parts of the If statement. Before then, lets take another look at the Syntax of the If statement.

If (Condition is true) 
{Execute the codes here}

Here is our first example

If (1 -gt 2) 
{Get-Command}

You can have the statement in a single line as shown below

 If (1 -gt 2) {Get-Command} 

Now copy the command above into PowerShell. Then press Enter.

Powershell If Else Explained: Syntax and Examples

As expected, the Get-Command in the {} did not run. Why? Because the condition is FALSE (1 -gt 2 is false)

We can reverse this command by simply adding a “!” before () block.

If (!(1 -gt 2)) {Get-Command}  

Surprise! Get-Command have now been executed. Reason? We reversed the output of the condition test, (1 -gt 2).

To make it clearer, lets see the result of

!(1 -gt 2) 

Here it is, TRUE!

With this basic example, you can complete any complex Windows task with a PowerShell IF statement script. The principle is the same – test whether the values in () are TRUE OR FALSE, then execute the code in {}. It is that simple!

In the next section, I will give real life Windows Admin examples.


PowerShell If Else Example 2: Create a Folder If It Does not Exist

In this example, I will walk you through how to write a simple Powershell script that will create a folder if it does not exist.

As usual, we will begin with the Syntax of the If statement.

If (Condition is true) 
{Execute the codes here}

First, lets add the condition that tests whether a folder does NOT exist. We will use the Test-Path command to check if a “PowerShell Folder 1” DOES NOT exists in the path “F:\PS If” folder.

Here is the command to check if “PowerShell Folder 1” folder DOES NOT exists in “F:\PS If” folder.

!(Test-Path "F:\PS If\PowerShell Folder 1") 

See the result below:

PowerShell If Else Example 2: Create a Folder If It Does not Exist - result

The command says if “F:\PS If\PowerShell Folder 1” DOES NOT exist, return TRUE.

Before we add this code into the If Syntax, lets look at the If Syntax one more time:

If (Condition is true) 
{Execute the codes here}

So far we have replaced “Condition is true” with “Test-Path !(“F:\PS If\PowerShell Folder 1″)”

This is where we are with the script that creates a folder if it does not exist.

If ( !(Test-Path "F:\PS If\PowerShell Folder 1") ) 
{Execute the codes here}
All I did above is to replace “Condition is true” with with “Test-Path !(“F:\PS If\PowerShell Folder 1″)” in the If Syntax.

Next, I will add the command that creates the folder into the {} block. I will use the New-Item Powershell cmdlet (command) to create the folder. Here is the command:

New-Item -ItemType "directory" -Path "F:\PS If\PowerShell Folder 1"

Next, I will enclose it in the {} block.

{New-Item -ItemType "directory" -Path "F:\PS If\PowerShell Folder 1"}

Finally, I will bring the () and {} parts of my If statement together.

If ( !(Test-Path "F:\PS If\PowerShell Folder 1") ) 
{New-Item -ItemType "directory" -Path "F:\PS If\PowerShell Folder 1"}

To be able to copy the command and run it in PowerShell console, move both paths into a single line:

 If ( !(Test-Path "F:\PS If\PowerShell Folder 1") ) {New-Item -ItemType "directory" -Path "F:\PS If\PowerShell Folder 1"}  
Summary
What I have done so far is exactly what I did in the first example: Add a condition that checks whether a folder DOES NOT exist. Then create the folder. If the folder exists, it will NOT be created. See the result below:

PowerShell If Else Example 3: Multiple If Conditions

In the final example, I want to use “If”, “ElseIf” and “Else” in one statement. This example is a continuation of the previous example.

To refresh your memory, here is the Syntax:

If (Condition 1 is true) 
{execute the code here}
ElseIf (Condition 2 is true)
{Execute the code here instead}
Else
{DO Nothing}
In real world, you can omit the last Else block.

In this example, I will check if the folder path “F:\PS If\PowerShell Folder 1” exists. Then create the folder if it DOES NOT. In the second ElseIf block, I will check if the folder path “F:\PS If\PowerShell-Folder” exists. Create it if it DOES NOT.

Here is the full script

If ( !(Test-Path "F:\PS If\PowerShell Folder 1") ) 
{New-Item -ItemType "directory" -Path "F:\PS If\PowerShell Folder 1"}

ElseIf (!(Test-Path "F:\PS If\PowerShell-Folder") )
{New-Item -ItemType "directory" -Path "F:\PS If\ PowerShell-Folder"}

I will now move all the commands into a single line.

You can use a PowerShell scripting editor like PoserShell ISE to execute the commands without having to move them to a single line.
If ( !(Test-Path "F:\PS If\PowerShell Folder 1") ) {New-Item -ItemType "directory" -Path "F:\PS If\PowerShell Folder 1"} ElseIf  (!(Test-Path "F:\PS If\PowerShell-Folder") ) {New-Item -ItemType "directory" -Path "F:\PS If\PowerShell-Folder"}  

See the result below

From the result, you will notice that the command only created PowerShell-Folder as it did not exist. The first folder PowerShell Folder 1 was NOT created by this last command because the folder already existed.

Conclusion

Powershell If Else is a very useful statement for PowerShell scripting. I hope I have been able to simply it with this guide. If you have any question or comment use the “Leave a Reply” form at the end of the page.

Better still, share your experience with other readers.

Other Helpful Guides

Additional Resources and References

  • Was this post Helpful?
  • YesNo

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

How to Add Bullet Points in Google Slides

How to Add Bullet Points in Google Slides (Android or iOS Apps or PC)

This Itechguide teaches you how to add bullet points in Google Slides. The guide offers steps to add bullet points in Google...
How to Create a Business Facebook Page without a Personal Account

How to Create a Business Facebook Page without a Personal Account

This Itechguide teaches how to create a business Facebook page without a personal account. There could be a...
How to Wrap Text in Google Sheets

How to Wrap Text in Google Sheets (from a PC or the Apps)

This Itechguide teaches you how to wrap text in Google Sheets. The guide offers steps to wrap text in Google Sheets from...
How to Change Birthday on Facebook

How to Change Birthday on Facebook (from the App or PC)

This Itechguide teaches you how to change birthday on Facebook. The guide contains steps to change birthday on Facebook from the Facebook...
Best Thrillers on Netflix

The 10 Best Thrillers on Netflix

The thrillers on Netflix is quite a large number of movies. Knowing the best thrillers to watch can be a challenge.

ADVERTISEMENTS

TRENDING POSTS

Remote Desktop Connection

Remote Desktop Connection an Internal Error Has Occurred [Fixed]

Introduction I recently received the error message "Remote Desktop Connection an Internal Error Has Occurred". It was strange because...

Find My Samsung: Register and Use Samsung Find my Mobile

Introduction Ever wondered how you could find your Samsung phone if you lost it? Find my Samsung or Samsung...
What is the Difference Between PowerShell and CMD?

Windows Powershell vs CMD: Differences and Similarities

Introduction This short guide compares Windows PowerShell vs CMD (Windows command prompt). I will cover the history and nature...
Spotify No Longer Supports this Version of Microsoft Edge

Spotify No Longer Supports this Version of Microsoft Edge [Fixed]

Introduction When you open Spotify web player on Microsoft Edge, you may receive the error message "Spotify No Longer...
Windows 10 Won't Boot

Windows 10 Won’t Boot With Black Screen? 3 Ways to Fix It

Why Won't Windows 10 Boot Up? If your Windows 10 stops with a black screen, the first question in...

BEST OF ITECHGUIDES

your pc ran into a problem and needs to restart

Your PC Ran Into a Problem and Needs to Restart [Fixed]

What Does "Your PC Ran Into a Problem and Needs to Restart" Mean? "Your PC ran into a problem...
iPhone SE vs iPhone 6s compared - which to buy

iPhone SE vs iPhone 6s Compared: Which to Buy

Introduction Considering whether to buy iPhone SE vs iPhone 6s? Not sure which is better? When I am trying...
Powershell Function

PowerShell Function: Syntax, Parameters, Examples

Introduction There are two types of PowerShell Functions, basic and advanced. A basic PowerShell Function is a list of...
Install and Configure Windows Deployment Services in Server 2019

Install and Configure Windows Deployment Services in Server 2019

Introduction This guide demos how to install and configure Windows Deployment Services in Server 2019 Steps...
How to Block People on Facebook

How to Block People on Facebook (from Facebook App or PC)

Introduction This guide demonstrates how to block people on Facebook. When you block someone, that...

ADVERTISEMENTS

RECENT POSTS

How to Logout of Amazon App

How to Logout of Amazon App (from Android, iPhone or Windows 10)

This Itechguide teaches you how to logout of Amazon app. The guide offers steps to logout of Amazon app for Android, for...
How to Turn off YouTube Notifications

How to Turn off YouTube Notifications (PC or YouTube Apps)

This Itechguide teaches you how to turn off YouTube notifications. The guide offers steps to turn off YouTube notifications from a PC...
How to Change YouTube Thumbnail

How to Change YouTube Thumbnail (PC or YouTube Studio App)

This Itechguide teaches you how to change YouTube thumbnail. The guide offers steps to change YouTube thumbnail from a PC or...
How to Add Bullet Points in Google Slides

How to Add Bullet Points in Google Slides (Android or iOS Apps or PC)

This Itechguide teaches you how to add bullet points in Google Slides. The guide offers steps to add bullet points in Google...
How to Change Shipping Address on Amazon

How to Change Shipping Address on Amazon

This Itechguide teaches you how to change shipping address on Amazon. The guide offers steps to change shipping address on Amazon:

MUST READ

Walmart Baby Registry

Walmart Baby Registry: Your Definitive Guide

Introduction Walmart Baby Registry gives expectant mothers a place to create a list of items they need for their...
we can t sign into your account

How to Fix “We Can’t Sign into Your Account” Error in Windows 10

Introduction You may receive "we can't sign into your account" error after upgrading to Windows 10. If this occurs...
Group Policy, GPResult, Group Policy Object and RSoP

Group Policy, Group Policy Object and RSoP Explained

Introduction This guide gives an overview of Group Policy, RSoP (Resultant Set of Policy) and Group Policy Objects.

Windows 7 Safe Mode: How to Start Windows 7 in Safe Mode

Introduction If need to perform some advanced troubleshooting on Windows 7, then you may need to start Windows 7...
How to Uninstall a Program in Windows 10

How to Uninstall a Program in Windows 10 (3 Methods)

Introduction This guide demos how to Uninstall a Program in Windows 10. Options to Uninstall...

LATEST DEALS

Exclusive Student Offer_Save 10% on selected Surface devices

By using this website you agree to accept our Privacy Policy and Terms & Conditions