If-Else Statement

When we need to execute the block of statements either when the condition is true or when the condition is false, we must use the if-else statement.

If the condition, which is a Boolean expression evaluates to True, then the statements inside the ‘if‘ body will be executed. And if the condition evaluates to false, then the statements inside the ‘else‘ body will be executed.

Syntax of If-Else Statement

Flowchart of If-Else Statement

PowerShell If-Else Statement

Examples

The following examples illustrate how to use the if-else statement in PowerShell:

Example1: In this example, we can check that the number in the variable is even or odd. If the number is even, then prints Even, otherwise Odd.

Output:

The number is Odd  

Example2: In this example, we will check that the number is negative or positive number.

Output:

The entered number is negative  

Example3: In this example, we will check that a person is eligible for voting or not.

Output:

A person is eligible for voting.   

Example3: In this example, we will check the greatest number in two variables.

Output:

The value of variable n2 is greater.  

Next TopicElse-if Statement

Previous articleLearn MS Word Tutorial
Next articleWhat is PowerShell cmdlet