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.

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

ADVERTISEMENTS

FEATURED POSTS

How to Share Amazon Wish List

How to Share Amazon Wish List

This Itechguide teaches you how to share Amazon Wish List. The guide covers steps to share Amazon Wish List from a PC...
How to Pay with PayPal on Amazon

How to Pay with PayPal on Amazon

This Itechguide teaches you how to pay with PayPal on amazon. The guide covers 2 options to pay with PayPal on amazon....
How to Export Contacts from Outlook

How to Export Contacts from Outlook

This Itechguide teaches you how to export contacts from Outlook. The guide covers steps to export contacts from Outlook (Windows 10) or...
Best 90s Movies on Netflix

The 10 Best 90s Movies on Netflix

This Itechguide reviews the 10 best 90s movies on Netflix. The movies are listed in reverse order – with the 10th movie...
How to Clear Search History on Instagram

How to Clear Search History on Instagram

This Itechguide teaches you how to clear search history on Instagram. The guide covers steps to clear search history on Instagram from...

AMAZON DEALS

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

ADVERTISEMENTS

BEST OF ITECHGUIDES

How to Untag Someone on Facebook

How to Untag Someone on Facebook

This Itechguide teaches you how to untag someone on Facebook. The guide covers steps to untag someone on Facebook from the Facebook...
pc gaming controllers

iTechGuides’ Top 10 PC Gaming Controllers

There are so many games you can play on your PC. No matter the game you desire to play, you need a...
this accessory may not be supported

This Accessory May Not be Supported [Fix]

What Does This Accessory May Not be Supported Mean? You may receive "this accessory may bot be supported" error...
How to Tag Someone on Instagram

How to Tag Someone on Instagram

This Itechguide teaches you how to tag someone on Instagram. The guide covers steps to tag someone on Instagram from Android or...
Best Mystery Movies on Netflix

Our 10 Best Mystery Movies on Netflix

This Itechguide reviews the 10 best mystery movies on Netflix. Furthermore, the movies are listed in reverse order – with the 10th...

RECENT POSTS

5 Best Bluetooth Headphones Under 100

5 Best Bluetooth Headphones Under $100

This Itechguide reviews the 5 best Bluetooth headphones under 100 (USD). The best headphone is reviewed last, starting with the 5th on...
How to Search for a Word in Google Docs

How to Search for a Word in Google Docs

This Itechguide teaches you how to search for a word in Google Docs. The guide covers steps to search for a word...
How to Create a Folder in Google Docs

How to Create a Folder in Google Docs

This Itechguide teaches you how to create a folder in Google Docs. The guide covers steps to create a folder in Google...
How to Check Amazon Gift Card Balance

How to Check Amazon Gift Card Balance

This Itechguide teaches you how to check Amazon gift card balance. The guide covers steps to check Amazon gift card balance from...
How to Remove Google Account from Phone

How to Remove Google Account from Phone

This Itechguide teaches you how to remove Google Account from phone. The guide covers steps to remove Google Account from Android or...

AMAZON DEALS

MUST READ

How to Take Ownership of Folder in Windows 10

How to Take Ownership of Folder in Windows 10 (2 Methods)

Introduction This guide demos 2 methods to take ownership of folder in Windows 10. Options to...

Change User Name and Rename User Folder in Windows 10

Introduction There are so many reasons why you may want to change user name in Windows 10 or rename...
How to Restrict Someone on Facebook

How to Restrict Someone on Facebook

This Itechguide teaches you how to restrict someone on Facebook. The guide covers steps to restrict someone on Facebook from a PC,...
How to Cancel Amazon Order

How to Cancel Amazon Order

This Itechguide teaches you how to cancel Amazon order. Guide offers steps to cancel Amazon order from a PC (Amazon.com) or from...
powershell sleep

PowerShell Start-Sleep Command: Syntax, Examples

Introduction Powershell Sleep (Start-Sleep) Cmdlet is a very useful scripting tool. There may be instances when you want to...

AMAZON DEALS

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