Skip to content

PowerShell – If Else Statement


In PowerShell, the if statement is used for conditional execution. Here’s the basic structure of a if statement:

Syntax

Below is the syntax of an if…else if…else statement −

if ( condition ) { commands_to_execute }
      [ elseif ( condition2 ) { commands_to_execute } ]
      [ else {commands_to_execute} ]

If the boolean expression evaluates to true, then the block of code will be executed, otherwise, else block of code will be executed.

Here’s an example using an if-else statement:

$number = 10

if ($number -gt 5) {
    Write-Host "The number is greater than 5."
} else {
    Write-Host "The number is less than or equal to 5."
}

In this example:

  • $number = 10 assigns the value 10 to the variable $number.
  • The if statement checks if the value of $number is greater than 5.
  • If the condition ($number -gt 5) is true, it executes the code block within the first set of curly braces.
  • If the condition is false, it executes the code block within the else statement.

You can also add additional conditions using elseif if you have more than two possible outcomes:

$number = 10

if ($number -gt 15) {
    Write-Host "The number is greater than 15."
} elseif ($number -gt 5) {
    Write-Host "The number is greater than 5 but not greater than 15."
} else {
    Write-Host "The number is less than or equal to 5."
}

This code evaluates multiple conditions. If the first condition isn’t met, it checks the second condition, and if that’s not met either, it executes the else block.

You can use comparison operators (-eq, -ne, -gt, -lt, -ge, -le, etc.) to create conditions based on values or expressions in PowerShell’s if-else statements.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments