In this post we will be going through using if else statements.
If else statement in PowerShell evaluates a condition and executes code if the condition is true. If the condition is false, alternative code is executed.
If else can also be nested to create more complex scripts that handle multiple conditions and execute specific code for each condition.
If else follows the below format
if (condition) {
# code to execute if condition is true
}
else {
# code to execute if condition is false
}
If Statement
We will first go through using a single if statement, when using a if the part between the two () is the conditions which needs to be checked.
When using an if without an operator (eq, like, gt…..), the if will check that the variable is not empty.
The below shows the difference between the if statement when there is a value and no value.

When using an operator we can specify if the value matches then run the code.
$con = "True"
if($con -eq "True"){
Write-Host "Con is true" -ForegroundColor Green
}

If Else
Next we will go through using if and else. Adding else is a way to executed code if none of the conditions are meet.
$con = "True"
if($con -eq "True"){
Write-Host "Con is true" -ForegroundColor Green
}
else
{
Write-Host "Con is false" -ForegroundColor Red
}

We can add an elseif to add another condition, there is no limit to how many can be added but it can be a bit messy if there are two many if elseif’s. Also the first condition that is meet is will stop the rest from being tested.
$con = "True"
if($con -eq "True"){
Write-Host "Con is true" -ForegroundColor Green
}
elseif ($con -eq "False") {
Write-Host "Con is false" -ForegroundColor Red
}
else
{
Write-Host "Con does not meet condition" -ForegroundColor Yellow
}

If with additional operator
We can test multiple conditions by using different operator in the if statement. In the below we are using the -and operator to check that condition one is true and condition two is greater than 3

We can also use -or operator which allows for us to specify two expressions and returns true if either one of them is true.
$con1 = "True"
$con2 = "5"
if ($con1 -eq "True" -or $con2 -gt "6"){Write-Host "Condition are meet" -ForegroundColor Green}

If Null
We can also check for Null values in If statements, to check if a variable or result is null we use the $null variable.
The $null variable must be on the left side of the statement as if it not PowerShell may not

Using if statements in your PowerShell scripts creates a lot of possibilities for creating dynamic and responsive automation. They can be a bit confusing at the start but with a bit of practice and experimentation, if statements become powerful tools in your scripting.































































