C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
If-Else StatementWhen 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 StatementIf(test_expression) { Statement-1 Statement-2....... Statement-N } else { Statement-1 Statement-2....... Statement-N } Flowchart of If-Else StatementExamplesThe 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. PS C:\> $a=15 PS C:\> $c=$a%2 PS C:\> if($c -eq 0) >> { >> echo "The number is even" >> } else >> { >> echo "The number is Odd" >> } Output: The number is Odd Example2: In this example, we will check that the number is negative or positive number. PS C:\> $a=-10 PS C:\> if($a -lt 0){ >> echo "The entered number is negative" >> }else >> { >> echo "The entered number is positive" >> } Output: The entered number is negative Example3: In this example, we will check that a person is eligible for voting or not. PS C:\> $age=19 PS C:\> if($age -ge 20) >> { >> echo "A person is eligible for voting." >> } else >> { >> echo "A person is not eligible to vote." >> } Output: A person is eligible for voting. Example3: In this example, we will check the greatest number in two variables. PS C:\> $n1=150 PS C:\> $n2=200 PS C:\> if($n1 -gt $n2) >> { >> echo " The value of variable n1 is greater." >> } else >> { >> echo " The value of variable n2 is greater." >> } Output: The value of variable n2 is greater.
Next TopicElse-if Statement
|