How to Use if-else Statements in PowerShell?

As a PowerShell developer, you should know how to use the PowerShell If-Else Statements. In this tutorial, I will explain how to use if else statements in PowerShell using various real examples.

What is an If-Else Statement in PowerShell?

An if-else statement allows you to execute certain blocks of code based on whether a condition is true or false. It is a way to make decisions in your script. If the condition is evaluated to be true, the code inside the if block runs; otherwise, the code inside the else block executes.

Syntax

The basic syntax of an if-else statement in PowerShell is like below:

if (<condition>) {
    <statement1>
} else {
    <statement2>
}
  • <condition>: This is the expression that evaluates to either true or false.
  • <statement1>: This block of code executes if the condition is true.
  • <statement2>: This block of code executes if the condition is false.

Examples

Here are a few simple examples of PowerShell if-else statements.

Example 1: Basic If-Else Statement

Let’s start with a simple example where we check if a number is greater than 10 using the PowerShell script:

$number = 15

if ($number -gt 10) {
    Write-Output "The number is greater than 10."
} else {
    Write-Output "The number is 10 or less."
}

In this example, since $number is 15, which is greater than 10, the output will be:

The number is greater than 10.

You can also see the output in the screenshot below after I executed the above PowerShell script using VS code.

PowerShell If-Else Statement

Read PowerShell If Else Statement to Check if a Number is Between Two Values

Example 2: If-ElseIf-Else Statement

Sometimes, you may need to check multiple conditions inside a PowerShell script. PowerShell allows you to use elseif to handle such scenarios:

$number = 7

if ($number -gt 10) {
    Write-Output "The number is greater than 10."
} elseif ($number -eq 10) {
    Write-Output "The number is exactly 10."
} else {
    Write-Output "The number is less than 10."
}

Here, since $number is 7, the output will be:

The number is less than 10.

Comparison Operators:

Here are the comparison operators you can use.

OperatorDescriptionExample
-eqEqualsif ($a -eq $b)
-neNot equalif ($a -ne $b)
-ltLess thanif ($a -lt $b)
-leLess than or equalif ($a -le $b)
-gtGreater thanif ($a -gt $b)
-geGreater than or equalif ($a -ge $b)

Here is another example of how to use logical operators in PowerShell if else.

You can use logical operators (-and-or-not) to combine multiple conditions in a single if-else statement:

$age = 25
$hasLicense = $true

if ($age -ge 18 -and $hasLicense) {
    Write-Output "You are eligible to drive."
} else {
    Write-Output "You are not eligible to drive."
}

Since $age is 25 and $hasLicense is $true, the output will be:

You are eligible to drive.

You can see the above PowerShell script’s output in the screenshot below:

If-ElseIf-Else Statement PowerShell

Example 3: Nested If-Else Statements

You can also nest if-else statements to check more complex conditions. Here’s an example:

$number = 5

if ($number -gt 0) {
    if ($number -lt 10) {
        Write-Output "The number is between 1 and 9."
    } else {
        Write-Output "The number is 10 or greater."
    }
} else {
    Write-Output "The number is 0 or negative."
}

In this case, since $number is 5, the output will be:

The number is between 1 and 9.

Read PowerShell Data Types

If-Else Statements in PowerShell

If-Else statements are essential in PowerShell scripting for executing code based on different conditions.

The If Statement

The if statement is the building block of conditional logic in PowerShell. It checks whether a condition is true or false and executes code accordingly. For example:

if ($a -eq 5) {
    Write-Output "The value of a is 5"
}

In this example, if the variable $a is equal to 5, the script will output “The value of a is 5”. The comparison operator -eq checks for equality.

The Else Statement

The else statement works in conjunction with the if statement. It executes an alternative action if the if condition is false. Here’s how it looks:

if ($a -eq 5) {
    Write-Output "The value of a is 5"
} else {
    Write-Output "The value of a is not 5"
}

In this example, if $a is not equal to 5, the script will execute the code inside the else block and output “The value of a is not 5”.

Read Multiple Conditions in PowerShell If Else Statement

Using ElseIf

Sometimes, you need to check multiple conditions. The elseif statement allows for this flexibility. It checks another condition if the if statement is false:

if ($a -eq 5) {
    Write-Output "The value of a is 5"
} elseif ($a -eq 10) {
    Write-Output "The value of a is 10"
} else {
    Write-Output "The value of a is neither 5 nor 10"
}

Here, the script checks if $a equals 5 first. If not, it checks if $a equals 10. If neither condition is met, the else block executes.

The Importance of Braces

Braces {} are crucial in PowerShell’s conditional statements. They define the block of code to execute for each condition. For example:

if ($a -eq 5) {
    Write-Output "Inside if block"
    # More actions here
}

Braces help keep the code organized and readable. Omitting braces can lead to unexpected behavior, especially when multiple lines of code are inside each block.

Read How to Handle Errors with Try-Catch in PowerShell?

How to Implement If Else Conditions in PowerShell

To work with If Else conditions in PowerShell, you should know how to perform simple condition checks, evaluate multiple conditions, and test for specific cases.

Simple Condition Checks

A simple If Else condition starts by setting up an If statement that evaluates an expression. If the expression is true, the code within the block runs. An Else statement can be added to execute code when the condition is false.

$number = 10
if ($number -eq 10) {
    Write-Output "Number is 10"
} else {
    Write-Output "Number is not 10"
}

In the example above, the -eq operator is used to compare the variable $number. If $number equals 10, the first block executes, showing that the condition is true. If not, the Else block runs.

Multiple Condition Evaluation

To check several conditions, use elseif or combine multiple expressions with the -and or -or operators. This helps handle more complex logic in a PowerShell script.

$age = 25
if ($age -lt 13) {
    Write-Output "Child"
} elseif ($age -lt 20) {
    Write-Output "Teenager"
} else {
    Write-Output "Adult"
}

Here is the output in the screenshot below:

Multiple Condition in PowerShell if else

Alternatively, multiple conditions can be combined within a single If statement:

$score = 85
if ($score -ge 90 -and $score -le 100) {
    Write-Output "Grade A"
} elseif ($score -ge 80 -and $score -lt 90) {
    Write-Output "Grade B"
} else {
    Write-Output "Below Grade B"
}

In the above, -ge and -le operators ensure a range is checked to assign grades based on the score variable.

Read PowerShell Functions: Return Values and Multiple Values

Nested If Statements in PowerShell

In PowerShell, nested if statements are used to perform multiple levels of decisions within a single block. This allows the execution of different actions based on several conditions. Here is a PowerShell script.

if ($var -gt 10) {
    if ($var -lt 20) {
        Write-Output "Value is between 10 and 20"
    } else {
        Write-Output "Value is greater than or equal to 20"
    }
} else {
    Write-Output "Value is 10 or less"
}

How to Use If with Switch Cases in PowerShell

Switch statements in PowerShell can be combined with if statements to simplify decision trees with multiple branches. A switch statement evaluates a variable against a list of cases, making it easier to handle specific conditions.

Look at the example below:

switch ($input) {
    "Case1" { Write-Output "This is Case 1" }
    "Case2" {
        if ($subCondition -eq $true) {
            Write-Output "This is Case 2 with a sub-condition"
        } else {
            Write-Output "This is just Case 2"
        }
    }
    default { Write-Output "No matching case" }
}

Check out PowerShell If-Else String Comparison

PowerShell if else statement examples

Now, let me show you a few real examples of how to use the PowerShell if-else statement as an administrator.

Example 1: Checking Disk Space

In a system administration scenario, you might need to check the available disk space on a server and take action if it falls below a certain threshold.

Here is the complete PowerShell script where I have used the if else statement.

$disk = Get-PSDrive -Name C
$freeSpaceGB = [math]::Round($disk.Free / 1GB, 2)

if ($freeSpaceGB -lt 10) {
    Write-Output "Warning: Free disk space is below 10 GB. Current free space: $freeSpaceGB GB"
    # Add code to send an alert email or clean up disk space
} else {
    Write-Output "Disk space is sufficient. Current free space: $freeSpaceGB GB"
}

In this example, the script checks the free disk space on the C: drive. If the free space is less than 10 GB, it outputs a warning message. Otherwise, it confirms that the disk space is sufficient.

Example 2: User Account Status

You might need to check the status of a user account in Active Directory and disable it if it is inactive. This is a very common requirement for an Azure administrator.

$user = Get-ADUser -Identity "jdoe" -Properties LastLogonDate

if ($user.LastLogonDate -lt (Get-Date).AddMonths(-6)) {
    Disable-ADAccount -Identity $user.SamAccountName
    Write-Output "User account $($user.SamAccountName) has been disabled due to inactivity."
} else {
    Write-Output "User account $($user.SamAccountName) is active."
}

This script checks the last logon date of a user account. If the user has not logged in for the last six months, the account is disabled. Otherwise, it confirms that the account is active.

Example 3: Service Status Monitoring

In this example, you check the status of a Windows service and restart it if it is not running.

Here is the complete PowerShell script, and you can see how I used the if else statement.

$serviceName = "wuauserv" # Windows Update Service
$service = Get-Service -Name $serviceName

if ($service.Status -ne 'Running') {
    Restart-Service -Name $serviceName
    Write-Output "Service $serviceName was not running and has been restarted."
} else {
    Write-Output "Service $serviceName is running."
}

Here, the script checks if the Windows Update service is running. If it is not, the script restarts the service and outputs a message. If the service is already running, it simply confirms the status.

Read How to Use Exclamation Mark in PowerShell If Statements?

Example 4: File Existence Check

You might need to verify if a specific file exists and take action based on that.

This is a very common requirement for a PowerShell administrator, and you can follow the below script.

$filePath = "C:\Scripts\backup.ps1"

if (Test-Path $filePath) {
    Write-Output "The file $filePath exists. Proceeding with execution."
    # Add code to execute the script or perform other actions
} else {
    Write-Output "The file $filePath does not exist. Please check the path."
}

In this example, the script checks if a backup script file exists at the specified path. If the file exists, it outputs a message and can proceed with further actions. If the file does not exist, it outputs an error message.

I hope this tutorial and the examples will help you learn how to use the if-else statement in PowerShell. If you still have questions, leave a comment below.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.