C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
If StatementWhen we need to execute the block of statements only when the specified condition is true, use an If statement. This statement consists of a Boolean or logical expression followed by one or more statements. If the condition, which is a Boolean expression evaluates to True, then the statements inside the If statement will be executed. And if the condition evaluates to False, then the first statement after the end of if statement will be executed. Statements inside the 'if' body can be a single statement or a code of block enclosed by the curly brackets '{}'. Syntax of If statementThe following is the syntax of If statement: If(test_expression) { Statement-1 Statement-2....... Statement-N } Flow chart of If statementExamplesThe following examples illustrate the use of the If statement in PowerShell: Example1: In this example, we will check the number in the variable 'a' is even number. If a number is even, then print a message. PS C:\> $a=16 PS C:\> $c=$a%2 PS C:\> if($c -eq 0) >> { >> echo "The number is even" >> } Output: The number is even Example2: In this example, we will check the value of variable 'a' is greater than the value of variable 'b'. PS C:\> $a=25 PS C:\> $b=20 PS C:\> if($a -gt $b) >> { >> echo "The value of variable a is greater than the value of variable b" >> } Output: The value of variable a is greater than the value of variable b Example3: in this example, we will check the strings in variable 'a' and 'b' are same. PS C:\> $a="True" PS C:\> $b="True" PS C:\> if($a -eq "True") >> { >> echo " Both the strings are equal". >> } Output: True Example4: In this example, we will display the square of the number. If the number is smaller than 10 and greater than zero. PS C:\> $p=10 PS C:\> if(($p -st 10) -and ($p -gt 0)) >> { $z=$p*$p >> echo "The square of $p is $z". >> } Output: The square of $p is $z
Next TopicIf-Else Statement
|