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

    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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap