This tutorial explains how to use if-else conditional statements in Powershell with examples.

If else conditional statesmns allows to execute commands based on conditional expression result.

It supports command execution of branches in powershell based on conditional values.

Powershell provides the following types conditional statements

It provides the following features

  • simple if statements: executes commands inside if block when condition is True.
  • if else statements : executes commands inside if block when condition is True, else else block code executes.
  • if elseif else statements: This executes when condition inside is false, executes code block inside elseif block when condition is true. when none of conditions are True, else block command excutes

Simple If statements

Syntax

if (condition){
  # command execution
}

conditiona is evaluate to True or false.

if condition is true, commands inside a if block executed.

Example:

$marks=35
if($marks -le 35)
{
 write-host "Failed in a Exam"
}

if else statements

This is to execute commands based on conditional expression result.

commands inside if block are executed when condition is True else commands inside else block are execute when condition is False.

Syntax

if (condition){
  # command execution
} else {
    # Condition is false and  executes a commands

}

Example:

$marks=45
if($marks -le 35){
 write-host "Failed in a Exam"
 } else {
	write-host "Passed in a Exam"
}

if elseif else statements

This is to test multiple conditions, one of the condition is false, then other conditions are checked.

if (condition){
  # condition is truen, then command execution
}elseif( condition2) {
   # Condition is false a& condition2 is true, then  executes a commands
}
else {
   # Condition  and condition2 is false and  executes a commands
}

Example:

$marks=90

if($marks -le 35){
 write-host "Marks are less than 35"
}elseif($marks -le 50){
	write-host "Marks are less than 50"
}elseif($marks -le 60){
	write-host "Marks are less than 60"
}elseif($marks -le 90){
	write-host "Marks are less than 90"
}else{
 write-host "Marks are greater than 90"
}

Powershell Ternary Operator

There are no ternary operators in Powershell. You can assi

You can assign the variable with if condiional statement.

It Assign result of conditonal statements command execution to a variable

$marks=90

$result = if ($marks -le 35){"failed"} else { "Passed"}

write-host $result # Passed