Understanding If Else Statements in PowerShell

Understanding If Else Statements in PowerShell

One of the most basic ways to control code flow and logical selection is with the use of If-Else statements. This is otherwise known as conditional logic. In this tutorial, you will learn how to go about using if-else statements in your scripts.

Setup

If you have not already done so, open Windows PowerShell ISE.

Step one.

If-else statements are quite simple. Essentially it is much like deductive reasoning. IF today is cold, I will wear a jacket; if not (else), I won't need a jacket.

The following is an example of how an if-else statement would be written in PowerShell:

The code above is quite simple. Variable $a has been initialized to 7. We want the code to print out to the screen whether or not the variable is Greater than 4. So far, it will only print the message while variable $a's value is more than four which currently it is. If-else statements work with Boolean values (TRUE or FALSE) as well. Keeping this in mind, any zero value is FALSE and any non-zero is TRUE.

Step two.

The above code only has the "if" portion of the statement. While this is great, we also have to factor in when a condition evaluates to false. So we will change variable $a, to equal 2 and we will apply the "else" portion of the statement, which will state "Value is less than 4"

Example

    ($a –gt 4) {

Write-Host "Greater than 4!"

} else {

                Write-Host "Value is less than 4!"

}

   

Copy and Try it

When the script is ran, you will come to find that the statement evaluates to false, thus making the output stating that the value is less than 4, as shown in the image below:

Step three.

You can nest if-else statements within each other. The succeeding if-else statements are placing in the preceding statement's else statement. An example of nested if-else statements is presented in the code below:

Example

#Size comparison 
$size = "M"
If ($size –eq "S") {
                Write-Host "Small"
} 
else {
    If ($size –eq "M") {
                    Write-Host "Medium"
    } 
    else 
    {
         If ($size –eq "L") {
             Write-Host "Large"
        }
        else {
            Write-Host "Unknown Size"
        }
    }
}
    

Copy and Try it

Keep in mind to close the previous else's brackets, otherwise you will have broken code.

Remarks last but not least…

As you can see, if-else statements are relatively basic conditional selection statements. We build on conditional logic, as well as loops, in future tutorials. Join us next time for additional PowerShell tutorials. Till then