Skip to content

If/Else statement

If is a very simple conditional execution statement. To explain it, the following logic is used: If the following item in ( ) is true, then continue with . For items you want to not be true, there are methods of flagging for if not true.

.ps1
$FilePath = "D:\Secretlogs.txt"
if ($(Test-Path $FilePath) -eq $false ){
Write-host "No D:\ detected."
}
# We're not limited to $true, $false & $null however. Here are a few ways create an if not.
if (!(Test-Path $FilePath))
if (-not(Test-Path $FilePath))
# The following works, but needs some love. Our variable is a string. The below only checks if the value is not $null currently.
if ($FilePath)


So, that’s the very basics of if. But what about else if? Lets nest it a little so we can understand the behavior fully.

.ps1
- if ($Age -lt 18) # Always gets checked as it's an unnested if
- if ($UserConsent -eq $true) # Only gets checked if the first if is true.
- Write-host "Condition met" #Then do this
- if ($Country -ne 'US') # Always gets checked as it's an un-nested if
- Write-host "Condition met" # Then do this
- elseif ($Age -ge 65) # Only gets checked if the first value is not true
- if ($UserConsent -eq $false) # Only gets checked if the elseif is checked and true.
- Write-host "Condition met" # Then do this
- else
- Write-host "No Condition met" # Then do this.

The first branch required two statements to be true to execute The second branch only runs if the first if is not met, and then requires the second statement to be false. Finally, the else statement on the end requires no rules. It will run on ever item that was not met by any of the prior if or elseif statements. If/Else is easy to work with, and easy to read when not nested too deeply.


This example here shows how you might choose to start building a basic script using if, elseif and else.

.ps1
$WinFeature = Get-WindowsOptionalFeature -Online -FeatureName 'Microsoft-Hyper-V'
if ($($Feature.state -eq 'Enabled', 'Enabled Pending')) {
Write-Output "$Feature is currently $($Feature.State)"
}
elseif ($($Feature.state -eq 'Disabled', 'Disabled Pending')) {
Write-Output "$Feature is currently $($Feature.State). Attempting to Enable."
Enable-WindowsOptionalFeature -Online -FeatureName "$WinFeature" -All -NoRestart
}
else {
Write-output "Unhandled feature state met. Terminating without enabling."
}

Everything you wanted to know about the if statement About_Booleans Get-Help about_If about_Comparison_Operators