PowerShell If ElseIf Else
Conditional statements let a script make decisions. Based on a condition, the script takes one path or another — just like a road fork: if the condition is true, go this way; otherwise, go that way. The if, elseif, and else statements are the most fundamental decision-making tools in PowerShell.
The if Statement
The if statement checks a condition. If the condition is True, it runs the code block inside the curly braces. If the condition is False, it skips that block.
Syntax
if (condition) {
# Code runs only when condition is True
}
Example
$temperature = 38
if ($temperature -gt 35) {
Write-Host "It is very hot today."
}
Output:
It is very hot today.
The if-else Statement
The else block runs when the if condition is False. It handles the "otherwise" scenario.
Condition Check
|
v
True? ----YES----> Run if block
|
NO
|
v
Run else block
$marks = 45
if ($marks -ge 50) {
Write-Host "Result: Pass"
} else {
Write-Host "Result: Fail"
}
Output:
Result: Fail
The if-elseif-else Statement
Use elseif to check multiple conditions in sequence. PowerShell evaluates each condition from top to bottom and runs only the first matching block.
Check Condition 1
|
True? --> Run Block 1 --> Done
|
False
|
Check Condition 2
|
True? --> Run Block 2 --> Done
|
False
|
Run else Block --> Done
$score = 78
if ($score -ge 90) {
Write-Host "Grade: A"
} elseif ($score -ge 80) {
Write-Host "Grade: B"
} elseif ($score -ge 70) {
Write-Host "Grade: C"
} elseif ($score -ge 60) {
Write-Host "Grade: D"
} else {
Write-Host "Grade: F"
}
Output:
Grade: C
Multiple Conditions with Logical Operators
$age = 22
$hasID = $true
# Both conditions must be true
if ($age -ge 18 -and $hasID) {
Write-Host "Entry granted"
} else {
Write-Host "Entry denied"
}
# At least one condition must be true
$isAdmin = $false
$isSupport = $true
if ($isAdmin -or $isSupport) {
Write-Host "Access to support dashboard allowed"
}
Output:
Entry granted
Access to support dashboard allowed
Negation with -not
$serviceName = "wuauserv"
$service = Get-Service -Name $serviceName
if (-not ($service.Status -eq "Running")) {
Write-Host "$serviceName is NOT running. Starting it now..."
Start-Service -Name $serviceName
} else {
Write-Host "$serviceName is already running."
}
Checking Null and Empty Values
$userInput = ""
if ([string]::IsNullOrWhiteSpace($userInput)) {
Write-Host "Input is empty. Please enter a value."
} else {
Write-Host "Input received: $userInput"
}
Output:
Input is empty. Please enter a value.
Checking File and Folder Existence
$folderPath = "C:\Reports"
if (Test-Path $folderPath) {
Write-Host "Folder exists: $folderPath"
} else {
Write-Host "Folder not found. Creating it..."
New-Item -Path $folderPath -ItemType Directory
Write-Host "Folder created."
}
Nested if Statements
An if block can contain another if statement inside it. This handles multi-level conditions.
$userRole = "Admin"
$isActive = $true
if ($userRole -eq "Admin") {
if ($isActive) {
Write-Host "Active Admin: Full access granted"
} else {
Write-Host "Inactive Admin: Account locked"
}
} else {
Write-Host "Standard user: Limited access"
}
Output:
Active Admin: Full access granted
Inline if – Ternary-Style Using Conditional Expression
PowerShell 7 introduced the ternary operator for simple one-line decisions.
# Syntax: condition ? valueIfTrue : valueIfFalse
$age = 20
$status = $age -ge 18 ? "Adult" : "Minor"
Write-Host $status # Adult
For PowerShell 5.1 compatibility, use the if expression pattern:
$isOnline = $true
$label = if ($isOnline) { "Online" } else { "Offline" }
Write-Host $label # Online
Comparing Strings in Conditions
$environment = "Production"
if ($environment -eq "Production") {
Write-Host "WARNING: Running in Production!"
} elseif ($environment -eq "Staging") {
Write-Host "Running in Staging environment."
} else {
Write-Host "Running in Development environment."
}
Output:
WARNING: Running in Production!
Real-World Example – Disk Space Check
$drive = Get-PSDrive -Name C
$freeGB = [math]::Round($drive.Free / 1GB, 2)
Write-Host "Free disk space on C: $freeGB GB"
if ($freeGB -lt 5) {
Write-Host "CRITICAL: Less than 5 GB free. Take action immediately!" -ForegroundColor Red
} elseif ($freeGB -lt 20) {
Write-Host "WARNING: Disk space is running low." -ForegroundColor Yellow
} else {
Write-Host "Disk space is healthy." -ForegroundColor Green
}
Common Mistakes and Fixes
| Mistake | Problem | Fix |
|---|---|---|
if $x -eq 5 { | Missing parentheses | if ($x -eq 5) { |
if ($x == 5) | Wrong operator (C-style) | if ($x -eq 5) |
if ($x = 5) | Assignment, not comparison | if ($x -eq 5) |
| Opening brace on new line | Parse error in some cases | Keep { on the same line as if |
Summary
The if statement is the primary decision-making tool in PowerShell. The else block handles the default case when no condition matches. Multiple elseif blocks handle complex branching logic. Logical operators -and and -or combine conditions in a single check. The ternary operator in PowerShell 7 writes simple decisions on one line. Real-world scripts use conditionals constantly — for service checks, file existence tests, input validation, and environment-specific behavior.
