Logical statements If, Else, and ElseIf are used in PowerShell to check various conditions. The If statement is used to check a condition and perform a particular action if the condition is true. If the condition is not true (FALSE), you can use Else or ElseIf to perform another action.
Conditional constructs in PowerShell include the following operators:
- IF
- IF…ELSE
- IF…ELSEIF…ELSE
- SWITCH
Logical comparisons are the basis of almost all algorithmic programming languages. In PowerShell, you can use an If statement to execute blocks of code only if the specified condition is true.
Here are a few examples of the use of If-Else statements in PowerShell.
The most straightforward piece of PowerShell code that uses IF looks like this:
$isActive = $true
if ($isActive) {
Write-Output "Variable contains True "
}
The commands inside the curly braces {}
(called a ScriptBlock) will only be executed if the condition inside the IF is true.
In this example, the if ($isActive)
line compares the variable with the boolean values True and False. If the condition is met (variable $isActive = $true
), the code from the ScriptBlock construction – {…action …}
is executed.
If the condition is not met, then the code in the script block will be skipped.
Unlike IF, the ELSE statement is optional. If the result of the previous checks is False, the code in the ScriptBlock of the Else statement is executed.
$isActive = $true
if ($isActive) {
Write-Output "The value is True"
}
else {
Write-Output "The value is False"
}
When multiple values need to be checked, the ElseIf statement is used. The ElseIF statement can be used multiple times.
$isActive = $False
$company = "POWERADM"
if ($isActive) {
Write-Output "The first condition is true"
}
elseif ($company -eq “MSFT”) {
Write-Output " The first condition is not true"
Write-Output "Company: Microsoft"
}
elseif ($company -eq “AMZ”) {
Write-Output " The first condition is not true"
Write-Output "Company: Amazon "
}
else {
Write-Output " Both conditions are false"
}
This PowerShell script displays the message “Both conditions are false
“.
When there are many check conditions, it becomes inconvenient to use the If Else construct. It is better to use the logical Switch operator when there are a large number of conditions to be checked. You can combine a list of conditions into a single construct using the Switch statement. Switch compares the value being checked with each condition, and if it finds a match, performs the action.
The basic syntax for a PowerShell construct using the Switch statement is as follows:
Switch (value) {
condition 1 {action}
condition 2 {action}
condition x {action}
}