PowerShell If Elseif Else Statement Tutorial

PowerShell provides the if..else statements in order to execute PowerShell code for the specified conditions. The if..else statement simply works with boolean expressions where if the specified condition is True the related statement and code block is executed. If the specified condition is False the related statement and code block are not executed.

if..elseif..else Statement Syntax

The if..elseif..else statement can be used in different ways with different syntax. If only the if statement is used the syntax is very simple which is like below.

if(CONDITION){
   CODE
}
if(CONDITION){
   CODE
}
else{
   CODE
}
if(CONDITION){
   CODE
}
elseif(CONDITION){
   CODE
}
else{
   CODE
}
  • CONDITION is the condition which is evaluated as True or False according to the case. If the CONDITION is evaluated as True the given CODE block is executed.
  • CODE is the code block which is executed if the current if or elseif CONDITON is True.

if Statement Example

The if statement is used to check and execute a single block of code. The condition can be single or more to be checked for a single if statement. In the following example, we check if the $age is over 18 and print some messages.

$age = 20

if ($age -gt 18) {
    Write-Host "Age is over 18"
}

if..else Statement Example

The if..else statement is used to check condition and execute code block according to the returned value like True or False. The condition is checked with the if statement and if the condition returns True the if condition code block is executed. If the condition returns False the else code block is executed.

$age = 20

if ($age -gt 18) {
    Write-Host "Age is over 18"
}
else {
    Write-Host "Age is less than 18"
}

if..elseif.else Statement Example

The if..elseif..else statement can be used to check multiple conditions and executed multiple code blocks. The if is used to check the first condition and execute codeblock. Next elseif statemants are used to check other conditions and executed code blocks. Multiple elseif statements can be used. The if none of the provided conditions are met the else statement can be used to execute code. The last else statement is optional.

$name = "windowstect.com

if ($name -eq "windowstect.com") {
    Write-Host "windowstect.com"
}
elseif ($name -eq "linuxtect.com") {
    Write-Host "linuxtect.com"
}
else {
    Write-Host "Another website"
}
See also  How To Open Local Group Policy Editor In Windows (Windows 10, Windows Server)?

Leave a Comment