PowerShell If Else Statement: Syntax and Examples

Every useful PowerShell script makes decisions. Should this file be backed up or skipped? Is the service running or does it need to start? Did the command succeed or fail? These decisions are handled by conditional logic — and PowerShell if else statements are the primary tool for writing that logic. This guide covers the full if/elseif/else syntax, every comparison operator you’ll need, logical operators, testing file existence, and when to reach for switch instead.
Basic If Statement Syntax
The if statement evaluates a condition and runs the block only if it’s true:
$diskFreeGB = 8
if ($diskFreeGB -lt 10) {
Write-Warning "Low disk space: only $diskFreeGB GB free"
}
# The condition block must always use parentheses
# The body must always use curly braces
if ($diskFreeGB -gt 100) {
Write-Output 'Plenty of space'
}
WARNING: Low disk space: only 8 GB free
Both the parentheses around the condition and the curly braces around the body are mandatory. Omitting either causes a parse error.
Adding Else and ElseIf
Chain conditions with elseif and provide a fallback with else:
$cpuPercent = 78
if ($cpuPercent -lt 50) {
Write-Output 'CPU: Normal'
} elseif ($cpuPercent -lt 80) {
Write-Output 'CPU: Elevated'
} elseif ($cpuPercent -lt 95) {
Write-Warning 'CPU: High'
} else {
Write-Error 'CPU: Critical — investigate immediately'
}
CPU: Elevated
PowerShell evaluates each condition in order and runs only the first matching block. You can chain as many elseif branches as needed. The else block runs only if no previous condition was true.
Comparison Operators (-eq, -ne, -gt, -lt)
PowerShell uses named comparison operators rather than symbols. All are case-insensitive for strings by default:
-eq— equal-ne— not equal-gt— greater than-ge— greater than or equal-lt— less than-le— less than or equal-like— wildcard match (*,?)-match— regex match-contains— collection contains item-in— item is in collection
$status = 'Running'
$status -eq 'running' # True (case-insensitive)
$status -ceq 'running' # False (case-sensitive: -ceq, -cne, etc.)
$status -like 'Run*' # True (wildcard)
$status -match '^R\w+' # True (regex)
$allowedRoles = @('Admin', 'Operator', 'Viewer')
'Admin' -in $allowedRoles # True
$allowedRoles -contains 'Admin' # True
Logical Operators (-and, -or, -not)
Combine multiple conditions with logical operators:
$isAdmin = $true
$isLoggedIn = $true
$failCount = 3
# Both must be true
if ($isAdmin -and $isLoggedIn) {
Write-Output 'Full access granted'
}
# Either must be true
if ($failCount -gt 10 -or $isAdmin -eq $false) {
Write-Warning 'Access restricted'
}
# Negate a condition
if (-not $isAdmin) {
Write-Output 'Standard user — limited access'
}
Full access granted
Operator precedence: -not is evaluated first, then -and, then -or. Use parentheses to make complex conditions explicit: ($a -and $b) -or $c.
Testing File and Path Existence
A very common pattern is checking whether a file or folder exists before acting on it:
$logPath = 'C:\Logs\app.log'
$backupDir = 'C:\Backup'
# Check file exists
if (Test-Path $logPath) {
Copy-Item $logPath $backupDir
Write-Output 'Log backed up'
} else {
Write-Warning "Log not found: $logPath"
}
# Ensure a directory exists before writing
if (-not (Test-Path $backupDir)) {
New-Item -ItemType Directory -Path $backupDir | Out-Null
Write-Output "Created backup directory: $backupDir"
}
Created backup directory: C:\Backup
Test-Path returns a boolean ($true/$false), making it a natural fit for if conditions. Use -PathType Leaf to verify it’s a file, or -PathType Container to verify it’s a folder.
Switch Statement as Alternative
When you have many conditions testing the same variable, switch is cleaner than a chain of elseif statements:
$exitCode = 2
switch ($exitCode) {
0 { Write-Output 'Success' }
1 { Write-Warning 'General error' }
2 { Write-Warning 'Misuse of shell command' }
126 { Write-Error 'Permission denied' }
default { Write-Error "Unknown exit code: $exitCode" }
}
WARNING: Misuse of shell command
Use switch when you’re branching on values of a single variable. Use if/elseif when conditions are independent or involve different variables and complex expressions.
Common Errors and Fixes
-
Using = instead of -eq for comparison:
if ($status = 'Running')assigns the string to$statusand evaluates to the string itself (which is truthy), so the block always runs. Use-eqfor comparison:if ($status -eq 'Running'). -
Parentheses placement causes parse error: The condition must be in parentheses immediately after
if:if ($x -gt 0) { }. Missing or misplaced braces are the most common syntax errors for beginners. PowerShell’s error messages point to the line where it ran out of input, not always where the brace is missing.
Related Cmdlets / See Also
Wrapping Up
PowerShell’s if/elseif/else construct handles all conditional branching needs. Use -eq, -lt, -like, and the other named operators for comparisons — never bare = for equality testing. Combine with Test-Path for defensive file operations and with logical operators for multi-condition logic. When branching on a single variable with many values, consider switch for cleaner code.


