WindowsWindows Loving ItLoving It

[WORKING] PowerShell if-then Latest examples 2020

Here are some of the latest examples for PowerShell if-then. Use these for the latest examples in 2020 with Latest PowerShell.

PowerShell condition

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:

$a = “hi”

if($a -eq “hi”){“hello”}

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.

if condition basic statement
if condition basic statement

Now if we change the value in $a to “bye” we do not get the same output.  The following script will demonstrate that.

$a = “bye”

if($a -eq “hi”){“hello”}

The above script will provide the output as shown below.  In fact, the above script will provide no output what so ever.

if condition syntax
if condition syntax

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.

$a = “bye”

if($a -eq “hi”){“hello”}else{“take care”}

The above script will produce the below result.

else block
else block

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.

Leave a Reply

Your email address will not be published. Required fields are marked *