Working With If Else Statement in PowerShell

The logical operators If Else and Else are used to check conditions. The If statement is designed to check a condition and perform a specific action associated with that condition. If we met the specified condition, then one action is performed, if not, then another.

Operations

Conditional constructs in PowerShell include operators:

  • IF
  • IF…ELSE
  • IF…ELSEIF…ELSE
  • SWITCH

Example of If Else statement in PowerShell

 The simplest PowerShell construct with If statement looks like this:

$isActive = $true

If ($isActive) {Write-Output “The value is True”}

The commands inside the brackets {} (called ScriptBlock) are executed only if the conditions inside the if () are met.

In our example, the line if ($isActive) compares the variable with the boolean values True and False. If the condition is met (variable $isActive = $true).

If you don’t met this condition, it will skipped the script block.

Else statement

Unlike the If statement, the Else statement is optional. The code from the ScriptBlock of the Else statement is executed when the result of the previous checks is False.

$isActive = $true

If ($isActive) {Write-Output “The value is True”}

Else {Write-Output “The value is False”}

Use of IfElse operator

The Elseif operator is used when you have to check multiple values. The Elseif operator can be used multiple times.

$isActive1 = $False

$company = “Solutionviews”

If ($isActive1)

{Write-Output “The first condition is True”}

Elseif ($company -eq “HPE”)

{Write-Output “The first condition isn’t True”

Write-Output “The company is HPE”}

Elseif ($company -eq “Apple”)

{Write-Output “The first condition isn’t True”

Write-Output “The company is Apple”}

Else

{Write-Output “Both conditions are not met”}

As you are executing this script, the message “Both conditions are not met” will be displayed on the PowerShell console.

If there are a lot of check conditions, it becomes inconvenient to use the If Else contract. With a large number of conditions to be checked, it is better to use the logical Switch operator, it allows you to combine a list of conditions in one construction.

It compares the tested value with each given condition. if it finds any match, then performs the ScriptBlock action associated with this condition.

The basic syntax for a PowerShell construct using a Switch statement looks like this:

Switch (value) {

Condition 1 {action}

Condition 2 {action}

Condition x {action}}

Leave a Reply

Your email address will not be published. Required fields are marked *




Enter Captcha Here :