Conditional structures: If, Else, ElseIf

I. Introduction

In this chapter, we'll be taking our first steps with conditional structures in PowerShell. We'll be looking at the following three statements: "If", "Else" and "ElseIf".

My aim is to explain how it works and to provide you with a number of examples that you can reuse in your scripts, and which are also there to give you a clear understanding of the concept.

II. What is a condition?

Before we even get into the syntax of conditional structures in PowerShell, or talk about the first example, let's start by answering a simple question: what is a condition? A condition, in the context of programming, is an expression that can be evaluated to give either true or false.

These conditions are the very foundation of the conditional structures such as "If", "Else" and "ElseIf" that we'll be studying in this chapter. They enable your script to make decisions based on the result of one or more conditions. For example, if a certain condition is true, then a certain block of code will be executed. Otherwise, another block of code will be executed.

In literary terms, and by way of example, here's what we can write:

If (It's sunny){ I'll make the trip by motorcycle } Else { I'll make the trip by car }

Based on the same principle:

If (My computer's battery is less than 10%.){ I'll connect the charger } Else ( I'll keep working on the battery)

The conditions will enable us to assess the situation and make a decision. In PowerShell, it's just like in real life: conditions can be as simple as a comparison between two values, or as complex as required to meet your specific needs. The aim is to cover as many situations and needs as possible, so that your script reacts appropriately to different situations.

III. If, Else, ElseIf syntax

A conditional structure block always begins with an "If" statement, and may be followed by one or more "Else/ElseIf" statements. There can also be an "If" statement on its own, but it's impossible to use "Else" and "ElseIf" statements on their own.

In French, these three instructions can be translated as follows:

  • If = If...
  • Else = Otherwise...
  • ElseIf = Otherwise if...

Note: "If" and "ElseIf" can include one or more conditions, while "Else" accepts no conditions (it applies when all conditions are false).

A. If condition in PowerShell

The syntax of a simple "If" conditional structure is as follows:

If(condition)
 { 
 # block of code: instructions to be executed if condition is true
 }

The "condition" part allows you to test one or more conditions. If the condition is true, the code block will be executed. This block of code can contain another If (nested If conditions), a loop of another type or any other command: there are no restrictions here.

As an example, let's try to translate the following sentence into a conditional structure:

If $texte is equal to "IT-Connect", then we write "Welcome!

Which gives:

$texte = "IT-Connect"
If($texte -eq "IT-Connect") 
 { 
 Write-Output "Welcome!"
 }

Since our variable is equal to "IT-Connect", then the message "Welcome!" will be displayed in the console. If we modify the value of the "$texte" variable, this will no longer be the case.

We can tryusing an If condition with the "Test-Path" cmdlet, whose purpose is to check the existence of an element (a file, for example).

Let's assume that we're trying to verify the existence of the file "C:\Windows\System32\drivers\etc\hosts". If the file exists, we'll simply return a confirmation message (and only then).

If((Test-Path -Path "C:WindowsSystem32driversetchosts") -eq $True) 
  { 
    Write-Output "Le fichier existe sur l'ordinateur local"
  }
PowerShell - If condition example

The"Test-Path" commandreturns true if the file exists, or false if the file doesn't exist, so we need to check that the result is "true", hence the use of the"-eq" equality comparison operator.

But, in the end, this test is optional, since the code will only be executed if the condition is true, and the "If" statement will be able to directly interpret the result returned by "Test-Path". So, in this case, we can write :

If(Test-Path -Path "C:\Windows\System32\drivers\etc\hosts") 
  { 
    Write-Output "Le fichier existe sur l'ordinateur local"
  }

B. If / Else conditions in PowerShell

Now we'll add an additional condition: "Else". We're going to evolve our two previous examples.

First of all, we're going to write a code corresponding to this sentence:

Si $texte est égal à "IT-Connect" alors on écrit "Bienvenue !" sinon on écrit "Oups !".

This will result in :

$texte = "Microsoft"

If($texte -eq "IT-Connect") 
 { 
 Write-Output "Welcome!"
 }
Else
 {
 Write-Output "Oops!"
 }

We can then develop the second example on the same principle: if the file doesn't exist, we indicate this in the console.

If(Test-Path -Path "C:\Windows\System32\drivers\etch\osts") 
    { 
       Write-Output "Le fichier existe sur l'ordinateur local"
    }
Else
    {
       Write-Output "Le fichier est introuvable !" 
    }

Each time, only one block of code is executed: it's impossible for both the "If" and "Else" code to be executed. One or the other must be executed, depending on the evaluation of the condition.

C. If / ElseIf / Else conditions in PowerShell

Let's continue to develop our first example. At present, we only act in the case where "$texte" is equal to "IT-Connect". Now let's imagine that we also want to handle the case where "$texte" equals "www.it-connect.fr".

To include this second test independently of the first, we need to use the "ElseIf" statement and then end with "Else" to handle all other cases.

Which gives:

$text = "www.it-connect.fr"

If($text -eq "IT-Connect") 
 { 
 Write-Output "Welcome!"
 }
ElseIf($text -eq "www.it-connect.fr ")
 { 
 Write-Output "Welcome to www.it-connect.fr!"
  }
Else
 {
 Write-Output "Oops!"
 }

It's important to note that the "Else" statement must always be the last one if you wish to include one or more "ElseIf" statements.

The "Else" instruction is not mandatory. We can be satisfied with "If" and "ElseIf" (but beware of the possible impact on script operation). Simply delete the "Else" instruction:

$texte = "www.it-connect.fr"

If($texte -eq "IT-Connect") 
 { 
 Write-Output "Welcome!"
 }
ElseIf($texte -eq "www.it-connect.fr ")
 { 
 Write-Output "Welcome to www.it-connect.fr!"
  }

E. Multiple conditions

The previous "If/ElseIf/Else" example has the advantage of executing a different block of code depending on whether $texte = "IT-Connect" or $texte = "www.it-connect.fr". Nevertheless, we may need to execute the same code whether "$texte" equals "IT-Connect" or "www.it-connect.fr".

No problem at all! Simply include two conditions to be tested in the "If" statement, using "-or" ("or"). This will test whether one of the two conditions is true. If you want both to be true, you'll need to use "-and" : although you can mix the two.

Here is the syntax to use (watch out for parentheses):

$texte = "www.it-connect.fr"

If(($texte -eq "IT-Connect") -or ($texte -eq "www.it-connect.fr")) 
 { 
 Write-Output "Welcome!"
 }
Else
 {
 Write-Output "Oops!"
 }

Here's another example using "-and" to test the value of two variables.

$counter1 = 10
$counter2 = 20

If(($counter1 -eq 10) -and ($counter2 -eq 20)) 
 { 
 Write-Output "Both counters are valid!"
 }

Note that the "-eq" operator for "equal" is not the only one that can be used in a conditional structure. Of course, you can also use the other comparison operators: -ne, -gt, -ge, -lt, -le.... as well as "-match" and "-like". This syntax can also be used in an "ElseIf".

Finally, here is an example where we will use the "-gt" and "-lt" comparison operators:

$Counter = 10

If($Counter -gt 0)
 {
 "$Counter is greater than 0"
 }
ElseIf($Counter -lt 0)
 {
 "$Counter is a negative number"
 }

F. If condition with a command-based test

As we saw with "Test-Path", a test in an "If" (or "ElseIf") does not have to include a comparison operator. In fact, we can include a command directly in an "If" condition.

For example, if we want to test the presence of a process, i.e. that the process exists (that it is running), we can use this syntax :

If(Get-Process -Name "explorer" -ErrorAction SilentlyContinue)
 {
 Write-Output "The explorer process is running!"
 }

Adding"-ErrorAction SilentlyContinue" prevents an error message from being displayed in the console if the process does not exist.

IV. Conclusion

We've just seen how to integrate conditional tests into a PowerShell script using "If-Else" and "If-ElseIf-Else". Thanks to the examples in this chapter, you should be able to use conditional structures in your PowerShell scripts. By mastering the use of conditions, you can create PowerShell scripts that are dynamic, flexible and capable of handling a variety of scenarios.