Learning PowerShell — Let’s Do It Together — Part 4

Kamran Saifullah
3 min readFeb 13, 2020

In this section we will take a look onto different conditional statements which are supported by PowerShell. Like other programming languages PowerShell also supports “IF”, “ELSE IF”, “ELSE”, “Ternary Operator” and “Switch Statement”. Let’s take a look onto these one by one.

For the sake of this section we will be utilizing “Windows PowerShell ISE”. Which comes pre-installed in Windows.

IF Statement

IF statement works the same like it does in other programming languages. It checks for the condition, if the condition is satisfied the code within the block is executed else the execution is moved out of the block.

Consider the following code in which there are two variables declared along with the values. The IF statement checks if the value in secondNum variable is greater than firstNum or not. If it is it will print out the number which is greater.

$firstNum = 10

$secondNum = 30

if ($secondNum -gt $firstNum) {

Write-Host “The “ + $secondNum + “ is greater”

}

We can see that indeed the value 30 is greater than 10. While the Write-Host cmdlet is used to print data onto the screen. It works same as printf, print, cout, echo etc.

IF-Else Statement

IF-Else statement is same as IF statement but with an addition of else statement. Consider the previous sample code but this time we will revert the condition which checks which value is greater than other.

$firstNum = 10

$secondNum = 30

if ($firstNum -gt $secondNum) {

Write-Host “The “ + $firstNum + “ is greater”

} else {

Write-Host “The $firstNum is not greater than $secondNum”

}

Else-IF Statement

Else-IF statement is used when we care about multiple conditions. We want to make sure that the either one of the conditions will be fulfilled. Consider the following code sample in which are are looking whether the value is greater, equal or less than the second value.

Switch Statement

This statement comes really handy when we want the user to select one of our given options. Switch statement is equivalent to multiple IF statements. Consider the following sample code which takes a value and checks if it matches any condition.

switch (3)

{

1 {“It is one.”}

2 {“It is two.”}

3 {“It is three.”}

4 {“It is four.”}

}

Ternary Operator

The ternary operator behaves exactly like IF-Else statement. If the condition is true, the first part will be executed else the second part will be executed. Consider the following sample code.

$var1 = 10

$var2 = 30

($var1 -lt $var2) ? “True” : “False”

This code only works on the systems having PowerShell Version 7!

--

--

Kamran Saifullah

Malware/RE/Firmware Analysis, App Sec/Off Sec, VAPT, Phishing Simulations/SE | Risk Management, IS Governance, Audits, ISO 27001 LI