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

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.

Advertisement

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

FEATURED POSTS

How to Share a Folder in Windows 10 (3 Methods)

Introduction This guide demos how to share folder in windows 10. It covers 3 methods. Options...

How to Map Network Drive in Windows 10 (5 Methods)

Introduction This guide demos 5 methods to Map Network Drive in Windows 10. Options to...
How to Install Windows 10 1909 Preview Build

How to Install Windows 10 19H2 Preview Build

Introduction If you are a member of Windows 10 Insider Program you can install Windows 10 19H2 Preview Build....

How to Sign in to Windows 10 with a Microsoft Account

Introduction When you installed Windows 10 you may have created and signed in with a local account. You can...
Disable IPv6 in Windows 10

How to Disable IPv6 in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to disable IPv6 in Windows 10: Disable IPv6 from...

Advertisement

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

Advertisement

BEST OF ITECHGUIDES

Dual WhatsApp account in one phone

How to Use Dual WhatsApp Accounts in One Android Phone

Introduction Most Android phones now support dual SIM. If your Android phone has 2 SIM cards you can configure...

DHCP vs Static IP: How to Set a Static IP or Enable DHCP in...

What is DHCP vs Static IP Address? This tutorial will compare the difference between DHCP vs Static IP addressing....
rdp an internal error has occurred server 2016

How to Fix “RDP an Internal Error has Occurred” in Server 2016

Introduction "RDP an internal error has occurred server 2016" may be fixed by: Performing physical...
Gmail Mark All as Read: How to Mark all Emails as Read on Gmail

How to Mark all Emails as Read on Gmail

Introduction If you receive a lot of emails that you do not wish to read, you may want to...
How to Make a Scatter Plot in Excel

How to Make a Scatter Plot in Excel

Introduction You make a scatter plot in Excel to compare 2 sets of data. Unlike a Line Chart, a...

RECENT POSTS

How to Enable Hyper-V in Windows 10 (3 Methods)

How to Enable Hyper-V in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to enable Hyper-V in Windows 10. To install Hyper-V...
RSAT Tools in Windows 10 Explained: Plus How to Install RSAT

RSAT Tools in Windows 10 Explained: Plus How to Install RSAT

Introduction Starting from October 2018 (1809) update, RSAT Tools became part of Windows 10. From this version of Windows...

How to Enable RSAT for Active Directory in Windows 10 (3 Methods)

Introduction This guide demos 3 methods to enable Active Directory in Windows 10. It is not exactly enabling "Active...
How to Install Windows 10 1909 Preview Build

How to Install Windows 10 1909 (19H2) Preview Build

Introduction Windows 10 1909 Preview is available for Windows Insiders. Made available early September, 2019 you have to be...
How to Install RSAT in Windows 10 (3 Methods)

How to Install RSAT in Windows 10 (3 Methods)

Introduction This guide demos how to Install RSAT in Windows 10. Starting with Windows 10...

How to Share a Folder in Windows 10 (3 Methods)

Introduction This guide demos how to share folder in windows 10. It covers 3 methods. Options...
Configure Map Network Drive with Group Policy

Map Network Drive in Windows 10 with Group Policy

Introduction This guide demos how to map network drive with group policy. This guide is...

How to Map Network Drive in Windows 10 (5 Methods)

Introduction This guide demos 5 methods to Map Network Drive in Windows 10. Options to...
How to Download Windows 10 ISO with Media Creation Tool

How to Download Windows 10 ISO with Media Creation Tool

Introduction This guide demos the steps to download Windows 10 ISO. You can download Windows 10 ISO with Media...

How to Install Windows 10 from Network Boot (Via WDS Server)

Introduction This guide demos how to install Windows 10 from network boot. The steps discussed in...

Advertisement

MUST READ

windows server 2016 won't boot after update

Windows Server 2016 Won’t Boot After Update? Here are 3 Fixes

Introduction This guide recommends 2 fixes if Windows Server 2016 won't boot after update: Rollback...
change computer name - rename a windows 10 pc

4 Methods to Rename (Change the Name of) a Windows 10 PC

Introduction This guide demos 4 methods you can use to change computer name for a Windows 10 PC. You...

Routing and Remote Access in Windows Server 2016 (Part 4): Configure Web Application proxy

Introduction This is part 4 of a 4-part "Routing and Remote Access" series. This part covers how to configure...
powershell windows 10

Frequently Asked Powershell Windows 10 Questions

This guide brings the top 8 Frequently asked Powershell Windows 10 questions. Get answers to common Windows 10 PowerShell FAQs…
how to install windows 10 1903 update manually

How to Install Windows 10 1903 Update Manually

Windows 10 1903 Update was released in May, 2019. But some users are not yet offered the update via automatic update. The...

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