PowerShell: If Else ElseIf Statements Examples

Note: This article assumes that you are familiar with conditional if-else statements and want to get familiar with the syntax used in Windows PowerShell.

Let's take a look at how to perform if-else and if-elseif-else statements to perform conditional logic.


Example 1: If-Else Statement

    Syntax:
    if (condition) {
        # code to execute if the condition is true
    } else {
        # code to execute if the condition is false
    }
    
    $age = 25
    
    if ($age % 2 -eq 0) {
        Write-Host "Your age is even."
    } else {
        Write-Host "Your age is odd."
    }
    

Example 2: If-ElseIf-Else Statement

    if (condition1) {
        # code to execute if condition1 is true
    } elseif (condition2) {
        # code to execute if condition1 is false and condition2 is true
    } else {
        # code to execute if both condition1 and condition2 are false
    }
    
    $num = 3
    
    if ($num -eq 0) {
        Write-Host "The number is zero."
    } elseif ($num -gt 0) {
        Write-Host "The number is positive."
    } else {
        Write-Host "The number is negative."
    }
If Else ElseIf PowerShell Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!