|

FEATURED POSTS

How to Change Outlook Password in 3 Different Ways

How to Change Outlook Password in 2 Easy Steps

Introduction Before you change your Outlook Password you have to first change it with your email provider. The reason...
spotify web player not working

Spotify Web Player Not Working [Fixed]

Introduction Spotify Web Player may stop working for you with the following error messages: "Spotify Web Player an Error...
DISM.exe /Online /Cleanup-Image /Restorehealth

DISM.exe /Online /Cleanup-Image /Restorehealth Explained

What is DISM.EXE /Online /Cleanup-image /RestoreHealth? "DISM.exe /Online /Cleanup-Image /Restorehealth" is a DISM command that repairs issue with the...
DHCP Relay agent

DHCP Relay Agent: Configuration in Windows Server 2016

What is a DHCP Relay Agent? A DHCP Relay Agent allows DHCP clients in a different network subnet to...
ForEach-Powershell

PowerShell ForEach: Syntax, Parameters, Examples

What is PowerShell ForEach? PowerShell ForEach (ForEach PowerShell) is a PowerShell construct used in iterating through values in a...

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...
PowerShell vs CMD

Powershell vs CMD: Differences and Similarities Compared

Introduction This short guide compares PowerShell vs CMD (Windows command prompt). I will cover the history and nature of...
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

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 Pivot Table

How to Make a Pivot Table in Excel

Introduction A Pivot Table allows you to analyze, summarize and calculate large data to help find relationships. With a...
Excel Not Equal

Excel “Not Equal” Comparison Operator: Syntax, Examples

Introduction Excel "Not Equal" is a Comparison operator that compares two values. "Not Equal" will return TRUE if the...
how to install windows 10

How to Install Windows 10: Step by Step with Pictures

What you need to Install Windows 10 To learn how to install Windows 10 you need the following:
NTFS Permissions with Share Permissions

NTFS Permissions with Share Permissions Compared

Introduction Combing NTFS permissions with share Permissions increases folder security within a network. Every Windows Administrator should have a...

RECENT POSTS

how to merge cells in excel

How to Merge Cells in Excel in 2 Easy Ways

Introduction You can merge two Cells in Excel using CONCATENATE function or the “&” (ampersand) operator. Though Excel has...
How to Make a Pivot Table in Google Sheets

How to Make a Pivot Table in Google Sheets

Introduction You can make a Pivot Table in Google Sheets to simplify analysis of complex data. A Pivot Table...
how to make Pivot Table

How to Make a Pivot Table in Excel

Introduction A Pivot Table allows you to analyze, summarize and calculate large data to help find relationships. With a...
RAID 3 (Redundant Array of Independent Disks) Explained

RAID 3 (Redundant Array of Independent Disks) Explained

What is RAID 3? RAID 3 is a RAID implementation that uses striping with a dedicated parity disk....
RAID 5 vs RAID 6

RAID 5 vs RAID 6: Differences, Benefits and Disadvantages

What is RAID 5 vs RAID 6? RAID 5 and RAID 6 uses striping with distributed parity technique. However,...
concatenate excel

Concatenate in Excel: How to Concatenate Columns and Strings

What is Concatenate in Excel? Concatenate in Excel is joining two strings into one continuous string. You can join...

How to Add in Excel (Excel Sum) with Examples

Introduction There are different ways to add numbers in Excel. You could simply select the cells containing the data....
Excel Count

Excel Count: How to Count in Excel With Examples

Introduction Excel COUNT Function is used for counting items in a worksheet. Excel COUNT also has the conditional function,...
powershell.exe -command

Powershell.exe Command: Syntax, Parameters and Examples

Introduction You may be wondering why write on Powershell.exe Command. Are there special commands for Powershell.exe? Yes! When you...
how to move columns in excel

How to Move Columns to Rows and Rows to Columns in Excel

Introduction If you receive some Excel data in columns, you can easily move the columns to rows in Excel...

MUST READ

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.

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...
Active Directory Domain Services

Active Directory Concepts & Administration

Introduction Active Directory (AD) is a Microsoft directory service that stores information about objects in a network. AD also...
mobile hotspot greyed out windows 10

Mobile Hotspot Greyed Out on Windows 10, iPhone or Android [Fixed]

Introduction If mobile hotspot is greyed out on windows 10, iPhone or Android it is likely that you do...
Outlook 365: Subscription, Installation and Set Up

Outlook 365: Subscription, Installation and Set Up

If you are reading this you are probably one of the many people asking a lot of question about outlook 365 -...

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

YOU MAY ALSO LIKE:

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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