Home ยป PowerShell If-Else Statement

PowerShell If-Else Statement

The if-else statement in PowerShell provides a mechanism to implement conditional logic, control the flow of execution based on the specified condition evaluates to true or false. It enables script to respond dynamically for making decisions and executing actions accordingly.

Syntax of the If-Else Statement

The syntax of the if-else statement in PowerShell is as follows.

if (condition) {
    # Code to execute if condition is true
else {
    # Code to execute if condition is false

In this syntax:

  • condition: represents the expression to evaluate. If the condition evaluates to true, the code within the if statement is executed. Otherwise, the code block within the else statement is executed.

Let’s understand the if-else statement in PowerShell with practical examples.

How to Validate Input Using If-Else Statement in PowerShell

$username = Read-Host "Enter username"
if ($username -eq "admin") {
    Write-Host "Welcome, Administrator!"
else {
    Write-Host "Access Denied. Invalid username."

In the above PowerShell script, the $username variable stores the input received from the user. The if statement checks if the username is equal to “admin” and if evaluates to ‘true‘, it will print the message as “Welcome, Administrator!”. Otherwise, it will execute the code within the else statement.

How to Handle Errors using If-Else Statement in PowerShell

$result = Invoke-Command -ComputerName "CORP-Server01" -ScriptBlock {
    # Code to perform operation on remote server
if ($result -eq $null) {
    Write-Host "An error occurred while executing the command."
else {
    Write-Host "Command executed successfully."

If-ElseIf-Else Statement in PowerShell

$value = 45

if ($value -gt 70) {
    Write-Host "value is greater than 70"
elseif ($value -lt 50) {
    Write-Host "value is less than 50"
else {
    Write-Host "value is $value"

In the above example, we have written if-elseif-else statement in PowerShell.

value is less than 50

Cool Tip: How to use Switch statement in PowerShell!


I hope the above article on how to use if-else statement in PowerShell is helpful to you. You can leverage the if-else statement to enhance script functionality, improve error-handling, and achieve automation objectives.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.