PowerShell’s if-statement is another syntax that determines the flow of execution control. In our previous post, we learned about loops, now we will learn about if condition statement in PowerShell.
People also search:
If statement Example:
This is a basic if statement that prints “hello” if the variable $a contains “hi”. Take note of the -eq switch is used to check if one side of the switch is equal to the other side of the switch.
The above script will give the following output.
Now if we change the value in $a to “bye” we do not get the same output. The following script will demonstrate that.
The above script will provide the output as shown below. In fact, the above script will provide no output what so ever.
Important conditional operators:
- -eq equals
- -ne not equals
- -gt greater than
- -ge greater than or equal
- -lt less than
- -le less than or equal
PowerShell if with else:
Thus far we have seen when to use the if-condition for the block to execute a certain block of a script but we have not seen how to execute a block that is mutually exclusive to the if-condition block.
For example, we have the below script that will show an output, unlike our previous case.
The above script will produce the below result.
Note how the script in the else block is executed when the condition fails. That happens to be the case with “take care” text. Since the value in $a is “bye” the condition fails and we get the text from the else block.
The PowerShell if-then is a fairly straight forward syntax. Using it a few times makes its utility clear. We are going to need it every time we want to check something. If we want to check it is morning or night, odd or even, the file exists or does not exist, we need condition check and we get just the luxury with the if-condition statement.
For more awesome posts, stay tuned to TecKangaroo.