PowerShell - if elseif else statements

by
Jeremy Canfield |
Updated: May 25 2024
| PowerShell articles
An if statement in PowerShell has the following structure.
if ( <condition> ) {
<do something>
}
elseif ( <condition> ) {
<do something>
}
else:
<do something>
}
For example.
if ($foo -eq "Hello") {
Write-Host "foo equals Hello"
}
elseif ($bar -eq "World") {
Write-Host "bar equals World"
}
else {
Write-Host "foo does not equal Hello, bar does not equal World"
}
Following are common conditions.
if the foo boolean is True | if ($foo -eq $true) |
if the foo variable is empty / null | if ($foo -eq "") |
if the foo variable equals Hello | if ($foo -eq "Hello") |
if the foo variable contains "Hello" |
if ($foo -match ".*Hello.*") |
If the foo variable does NOT contain "Hello" | if ($foo -notmatch ".*Hello.*") |
Did you find this article helpful?
If so, consider buying me a coffee over at