Bootstrap FreeKB - PowerShell - if elseif else statements
PowerShell - if elseif else statements

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 94c1ed in the box below so that we can be sure you are a human.