PowerShell IF ELSE Explained: Syntax, Parameters, and Examples

Photo of author

By Victor Ashiedu

Published

Are you wondering how to use IF ELSE in PowerShell? In this detailed guide, you’ll learn all there is no know about the IF-ELSE statement with examples.

Overview

PowerShell automation specialists use the IF statement to run code blocks if a specified conditional test evaluates to true. In addition to specifying one conditional text, you can specify more tests.

The additional set of conditional tests can only run if all previous tests evaluate to false. These additional conditional tests are specified using the ELSEIF conditional tests.

Moreover, anytime you run a conditional test and it evaluates to true, the IF, ELSEIF statement runs a code in its code block.

Finally, if none of the conditional tests evaluates to true, you can specify a final code block that runs. This final code block is defined using the ELSE statement.

If none of the things I said in this section made sense, do not give up yet. It will become clearer from the syntax section.

Syntax of PowerShell IF ELSE

Based on my explanation in the overview section, here is the basic syntax of a PowerShell IF-ELSEIF-ELSE statement.

IF (<conditional-test1>)
        {<statement list 1>}
    [ELSEIF (<conditional-test2>)
        {<statement list 2>}]
    [ELSE 
        {<statement list 3>}]

There are 3 basic elements of an IF-ELSEIF-ELSE statement:

  1. The IF block
  2. Followed by the ELSEIF block
  3. Finally, the ELSE block

In the overview section, I said that you can use a PowerShell IF statement to run a code block if a conditional test evaluates to true. You specify this first conditional statement in the IF block.

Then, I also said that you can specify additional conditional tests. You use the ELSEIF block to do this.

Finally, if none of the conditional tests evaluates to true, you can use the ELSE block to run a code.

Without any doubt, the PowerShell IF ELSEIF ELSE statement is one of the most powerful tools you’ll need for PowerShell scripting.

PowerShell IF ELSE Examples

Now that you have the basic knowledge about this PowerShell scripting statement, let’s dive into examples.

How to Use the Full PowerShell IF-ELSEIF-ELSE Blocks

The best place to kick off this example is to show you how to use the full PowerShell IF-ELSE-ELSE statement blocks.

Here is an example showing the basic use of the IF statement block.

$RefNum = 30
IF ($RefNum -gt 30) {                         
       Write-Host "The value, $RefNum is greater than 30."
    }
ELSEIF ($RefNum -eq 40) {
       Write-Host "The value, $RefNum is equal to 30."
}
ELSE {
  Write-Host "The value, $RefNum is not greater than 30 nor equal to 40"
   }

When I run the script in PowerShell ISE, here is the result…

How To Use The Full PowerShell IF-ELSE-ELSE

The IF statement block ran the command in the ELSE block. This means that the conditional test in the IFELSEIF blocks returned false.

Let’s examine the conditional statements, starting with the IF conditional test…

$RefNum -gt 30

This conditional statement returned false…

Also, the additional conditional, defined in the ELSEIF block returned false.

($RefNum -eq 40)

Since the two conditional tests defined in the IF and ELSEIF blocks returned false, the IF statement will execute the command in the ELSE block. Here is the command in the ELSE block.

Write-Host "The value, $RefNum is not greater than 30 nor equal to 40"

This statement writes information using the Write-Host command.

Although this example is basic, it illustrates how to use the IF statement block.

How to Use Multiple Conditions in IF ELSE Block

In the last example, I showed you a basic example of the application of the IF-ELSEIF-ELSE block.

In this example, I will show you how to use logical operators to specify multiple conditions in an IF statement block.

I got the problem I’ll share in this example from this stackoverflow.com post. The user wanted to know how to combine multiple conditions in an IF statement.

Specifically, this StackOverflow user wanted to know how to check that the currently logged user and the operating system meet a condition before a command runs.

In this example, I want to check if the logged-in user is “VictorAs”. In addition to that, I want to check if the operating system is Windows 11.

If the two conditions are met, I’ll run a command in the IF statement command block.

To make the script easy to understand, I’ll break it down. Firstly, here are the commands that will display the current OS version and the logged-in user.

(Get-ComputerInfo -Property WindowsCurrentVersion).WindowsCurrentVersion
(Get-WmiObject Win32_ComputerSystem).UserName

Here are the results of the two commands…

How To Use Multiple Conditions In PowerShell IF ELSE Block

As you can see from the screenshot, the first command returns a number. However, the second command returns a result in the format…

ComputerName\UserName

So, before I use the condition in a PowerShell IF ELSE statement, it is a good idea to return just the username. The first step to achieving this is to use the Split Method to separate the computer name and the user name.

Here is the command…

((Get-WmiObject Win32_ComputerSystem).UserName).split("\")

The command separates the computer name and the user name into an array…

To return the second value in the array, use the command below…

((Get-WmiObject Win32_ComputerSystem).UserName).split("\")[1]
How To Use Multiple Conditions In PowerShell IF ELSE Block

Finally, we have the two commands that we need for the PowerShell IF ELSE condition tests…

(Get-ComputerInfo -Property WindowsCurrentVersion).WindowsCurrentVersion
((Get-WmiObject Win32_ComputerSystem).UserName).split("\")[1]

If you recollect, I want to apply multiple conditions in the IF condition test block…

  1. Check if the OS version is Windows 11 (the version number of Windows 11 starts with 6
  2. Check if the person signed in to the computer is “VictorAs”

Here is the PowerShell IF ELSE statement…

IF ( (((Get-ComputerInfo -Property WindowsCurrentVersion).WindowsCurrentVersion) -LIKE "6*") -AND ((((Get-WmiObject Win32_ComputerSystem).UserName).split("\")[1]) -eq "VictorA") ) {
 Write-Host "The two conditions in the IF condition test block are true"

}

The result shows that the command in the command block ran…

How to Assign and Use Variables in IF ELSE Block

In the last example, I used the script below to show how to add multiple conditions to an IF statement.

IF ( (((Get-ComputerInfo -Property WindowsCurrentVersion).WindowsCurrentVersion) -LIKE "6*") -AND ((((Get-WmiObject Win32_ComputerSystem).UserName).split("\")[1]) -eq "VictorA") ) {
    Write-Host "The two conditions in the IF condition test block are true"

}

You’ll agree that adding all the commands into the IF condition test block is a bit complicated. What if there is a way we can make it less complicated?

The good news is that there is! I can save the commands in the IF condition tests in two variables as shown below…

$OSVersion = (Get-ComputerInfo -Property WindowsCurrentVersion).WindowsCurrentVersion
$UserName = ((Get-WmiObject Win32_ComputerSystem).UserName).split("\")[1]

Then, I will use the variables in the PowerShell IF ELSE conditional test. See the script below…

$OSVersion = (Get-ComputerInfo -Property WindowsCurrentVersion).WindowsCurrentVersion
$UserName = ((Get-WmiObject Win32_ComputerSystem).UserName).split("\")[1]
IF ( ($OSVersion -LIKE "6*") -AND ($UserName -eq "VictorA") ) {
    Write-Host "The two conditions in the IF condition test block are true"
}

The last script produced the same result as the last script…

How To Assign And Use Variable In PowerShell IF ELSE Block

Clearly, by adding the commands I used in the IF conditional tests, I made the entire script less complicated!

How to Compare Two Strings in an IF ELSE Block

If you want to compare two text strings to see whether they’re the same, you can use the -eq comparison operator. For example, I can use the command below to compare the two text strings…

"My name is victor" -eq "My name is victor"

However, this may not have many practical applications. One way I can think of that will make it practical is to use the Compare-Object cmdlet.

Here is an example…

Compare-Object "My name is victor" "My name is victor" -IncludeEqual

By default, the Compare-Object cmdlet will not return any information if the two objects are similar or equal. However, if you include the IncludeEqual parameter, the cmdlet returns equals.

Here is the result of the command in PowerShell…

The result of the Compare-Object cmdlet has two columns. The InputObject column displays the text strings that are the same or different from the two text strings you compared.

In this last example, the two text strings are exactly the same. So, the InputObject column displayed the text – “My name is victor” – which is common to both text strings.

Additionally, the command displays relevant information in the SideIndicator column. In this example, the Compare-Object cmdlet displayed the character, == in the SideIndicator column.

The == character shows equality. Now, let’s see the result of the Compare-Object command if the text strings are different.

Compare-Object "My name is victor" "My name is Ashiedu" -IncludeEqual

The result shows that when two strings compared with Compare-Object are different, the SideIndicator column displays the character => or <=.

How To Compare Two Strings In A PowerShell IF ELSE Block

This takes us to how we can compare two text strings in a PowerShell IF ELSE statement. We can use the information in the SideIndicator column in the condition test block of a PowerShell IF statement.

This will be the general syntax of an IF statement that includes Compare-Object in its condition test block…

IF (Compare-Object <object 1> <object 1>)
        {<statement list 1>}

I am aware that this syntax doesn’t make much sense. Let’s see if we can use some examples to make sense of the syntax.

In this example, I want an IF statement to perform an action if the two text strings, “My name is victor” and “My name is victor” are the same. To bring you along with me on this journey, do you recollect that the Compare-Object command returns a SideIndicator column?

Do you also recollect that this column returns == character if the two strings compared are the same? This is the character we test for in the IF statement.

But first, to make the IF statement less complicated, I’ll save the output of Compare-Object in a variable. Here is the command…

$comobj = Compare-Object "My name is victor" "My name is victor" -IncludeEqual

Moving on, we have seen that the result of the above command has an object called SideIndicator. In the PowerShell IF ELSE statement below, I want to test if the two strings are equal.

Then, if they are equal, I will perform a command. Otherwise, if they’re not equal, I will perform a different command.

$comobj = Compare-Object "My name is victor" "My name is victor" -IncludeEqual
IF ($comobj.SideIndicator -eq "==") {
    Write-Host "The two strings are the same"
}
ELSEIF (($comobj.SideIndicator -eq "=>") -OR ($comobj.SideIndicator -eq "<=")) {
   Write-Host "The two strings are different"
}
If you recollect, the SideIndicator property of the Compare-Object command returns “=>” or “<=” if the two strings compared are different.

Here is the result of the last script in PowerShell ISE. The IF statement ran the command in the IF command block.

In this example, I have shown you how to compare text strings to determine similarities or differences.

However, the Compare-Object has a limitation. For example, it does not tell you the actual text strings that are similar or different in the two text strings compared.

To fix this limitation, I built a custom PowerShell function called Compare-TextStrings. To learn more about how this function works and how to use it, visit PowerShell Function That Compares Two Text Strings (Compare-TextStrings).

How to Use the Contains Operator Or Method in an IF-ELSE Statement

In a recent article, I discussed PowerShell -Contains Operator And .Contains() Method extensively. You can use either the .Contains() method of the -Contains Operator in an IF statement.

I will use a very simple example to demonstrate how this works.

In this example, I want to check if a text file contains the word, “Short description”. Then, if it contains the word, I want to count the number of occurrences.

The first step is to extract the content of the text file with the Get-Content command. Then, I will save the file content in a variable called filecontent.

$filecontent = Get-Content D:\PS-Tutorial\about_Operators.txt

Then, I will use the PowerShell IF-ELSE statement to test if the file contains “Operators”.

$filecontent = Get-Content D:\PS-Tutorial\about_Operators.txt
IF ($filecontent.Contains("Short description")) {
   $count = ($filecontent | Select-String -Pattern "Short description" -AllMatches).Matches.Count
   Write-Host "The string was found 1 time(s) in the text file"
} ELSE{
 Write-host "The text file does not contain the string"
}

How to Use the -AND Operator in a IF-ELSE Statement

As you already know, you use the IF statement to test a condition, then if the test returns true, perform a task. In an IF statement condition check, you can test multiple conditions.

To test multiple conditions, use the -AND operator to combine the conditions. Below is the syntax of the IF statement with the -AND operator…

IF (<conditional-test1> -AND <conditional-test2>)
        {<statement list 1>}

In the above statement, the IF statement block will only execute the command in its command block if the two statements on both sides of the -AND operator are true.

Here is a simple example…

IF ((1 -lt 2) -AND (2 -lt 3)) {
   Write-Host "The two tests on both sides of the -AND operator are true" -ForegroundColor Red
}

And here is the result in PowerShell…

How To The -AND Operator In A PowerShell IF-ELSE Statement

How to Use IF-ELSE to Add an Object to an Array Conditionally

Let’s say I have an array that is a collection of Windows event log names.

$LogNames = @("System", "Application", "Security")

Also, let’s say that I want to add a new log name (Setup) to the list. But, I want to check that “Setup” is not in the array.

I’ll write the following PowerShell statements…

$LogNames = @("System", "Application", "Security")

IF (-not($LogNames.Contains("Setup"))) {

    [System.Collections.ArrayList]$LogNamesList = $LogNames

    $LogNamesList.Add("Setup")

}

The first line of the statement creates an array and saves the array in a variable called LogNames. Then, in line 2, I used the IF statement to check if the $LogNames array contains the “Setup”.

If you look closely, I added the character the -not operator before the $LogNames.Contains(“Setup”) statement converts the result to true if the array does not contain “Setup”.

Moving on to line 3, I converted the array to a System.Collections.ArrayList. Without converting the array to a System.Collections.ArrayList, the next command in line 4 will not work.

Talking about the command in line 4, this is where the magic happens. Specifically, the command uses the .Add() method of the System.Collections.ArrayList to add the object to the array.

Okay, enough talking, let’s run the commands already!

I will start by running the command in line 1:

$LogNames = @("System", "Application", "Security")

The result clearly shows that the array does not contain the object “Setup”.

How To PowerShell IF-ELSE To Add An Object To An Array Only If The Object Does Not Exist In The Array

Now, let’s run the command in the condition test block of the IF statement. First, I’ll run the command without the -not operator.

Then, I’ll run the command with the -not operator

($LogNames.Contains("Setup"))
-not($LogNames.Contains("Setup"))

As you can see from the screenshot below, the first command returned False. This is expected since we know that the array does not contain “Setup”.

However, as I mentioned earlier, to execute the command in the command block of the IF statement, the condition test block has to return True.

So, to change the result of the command from False to True, I included the -not operator. That takes us to the last two commands.

[System.Collections.ArrayList]$LogNamesList = $LogNames
$LogNamesList.Add("Setup")
$LogNamesList

I included the last command, $LogNamesList so that you can see that “Setup” is now added to the array. Here is the result in PowerShell…

How To PowerShell IF-ELSE To Add An Object To An Array Only If The Object Does Not Exist In The Array

Frequently Asked Questions

1. How do you write IF and ELSE in PowerShell?

The syntax of a PowerShell IF ELSE statement is:

IF (test a condition) {run a command}

2. How do I use multiple IF statements in PowerShell?

The answer to how you use multiple IF statements in PowerShell depends on what you’re trying to achieve.

If you want to test multiple conditions before performing an action. Then, you can add the multiple conditions within the IF statement’s condition test.

Here is an example:

IF ((1 -lt 2) -OR (2 -gt 3)) {“Perform an action”}

However, if you want to test conditions one at a time and then perform actions based on the outcome of each, you add the conditions in the ELSEIF block of the IF statement.

Here is an example:

IF (1 -lt 2) {“Perform an action 1”}
ELSEIF (2 -gt 3) {“Perform an action 2”}
ELSEIF (3 -lt 4) {“Perform an action 3”}


The difference between these multiple uses of IF statement conditions are that in the first statement, the conditions are tested in one go. However, in the second example, the first condition is tested first and if it is not true, the second condition will then be tested.

3. How do I compare values in PowerShell?

How you compare values in PowerShell depends on what you want to achieve. If you want to compare values and return True or False, use the.Equals() Method.

For example, the command below returns True.

(“My name is Victor”).Equals(“My name is Victor”)

On the contrary, if you want to compare two objects and return some information that confirms equal or different values o, you can use the Compare-Object command.

For example, the command below returns the results below the command

Compare-Object “My name is Victor” “My name is Victor” -IncludeEqual

Results:

InputObject SideIndicator
———– ————-
My name is Victor ==

4. What is $? in PowerShell?

The characters $? contains the execution outcome of the last command.

For example, if my last command resulted in an error, $? will display a False. However, if my last command was successful, $? will display a True.

In scripting, you may use these characters to determine if your last command ran successfully or returned errors.

5. How do I match a string in PowerShell?

The answer to this question is in the question! You use the -match operator to match a string in PowerShell.

Here is an example. This command returns True.

“My name is Victor” -match “My name is Victor”

Conclusion

The PowerShell IF ELSEIF ELSE statement is one of the statements you need to understand if you’re going to successfully use PowerShell to automate tasks.

The good news is that the statement is easy to use. Once you understand it, you can apply it to any applicable scripting situation.

The syntax is as simple as “IF (condition is true) {perform the action here} ELSE {perform the action here}”.

I hope I was able to make the IF statement really easy for you to understand! Don’t hesitate to leave your feedback by completing the “Leave a Reply” form found at the bottom of this page.

Alternatively, you can respond to the “Was this page helpful?” question below.

Finally, there are additional PowerShell resources in our Windows PowerShell Explained and Windows PowerShell How-To Guides pages. You may also find some scripts on our PowerShell Script Repository page useful.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

Leave a comment

Send this to a friend