PowerShell If & Else Statements
In PowerShell, the if and else statements are used to control the flow of execution based on conditions. These conditional statements allow you to execute specific blocks of code depending on whether a condition is true or false.
​
Basic Structure
The basic structure of an if statement in PowerShell is:
​
if (<condition>) { # Code to execute if the condition is true }
​
The <condition> is an expression that evaluates to either $true or $false.
If the condition is true, the code block inside the braces {} is executed.
​
​
Adding else
An else statement can be added to provide an alternative
block of code that runs when the if condition is false:
​
if (<condition>) { # Code to execute if the condition is true } else { # Code execute if condition is false }
​
Using elseif
If you have multiple conditions to check, you can use elseif to add additional conditions:
​
if (<condition1>) {
# Code to execute if condition1 is true
} elseif (<condition2>) {
# Code to execute if condition2 is true
} else {
# Code to execute if none of the above conditions are true
}
​
​
Example
Here’s a simple example that checks the value of a variable
and executes different blocks of code based on that value:
​
$number = 10 if ($number -gt 10) {
Write-Output "The number is greater than 10."
} elseif ($number -eq 10) {
Write-Output "The number is exactly 10."
} else {
Write-Output "The number is less than 10."
}
​
In this example:
​
-
If $number is greater than 10, the first block of code is executed.
-
If $number is exactly 10, the elseif block of code is executed.
-
If $number is less than 10, the else block of code is executed.
​
​
Conditions
Conditions in PowerShell can be any expression that returns
a boolean value. Some common comparison operators used
in conditions are:
​
-
-eq : Equals
-
-ne : Not equals
-
-gt : Greater than
-
-lt : Less than
-
-ge : Greater than or equal to
-
-le : Less than or equal to
​
​
Summary
PowerShell's if, else, and elseif statements are essential for controlling the flow of your scripts based on conditions. By using these statements, you can create dynamic and responsive scripts that execute different blocks of code depending on the conditions you specify.
​
A Basic If and Else Conditional Statement
$MyNumber="299"
If ($MyNumber -gt 200){
Write-host "The Value is Above 200"
}Else{
Write-Host "The Value is Not Above 200"
}
If and a Elseif for doing two conditionals
$Myteststring = "ScottHead"
If ($Myteststring.StartsWith("M")){
Write-host "It starts with an M"
}Elseif($Myteststring.StartsWith("S")){
Write-Host "It starts with an S"
}
Nested If Statement
$MyNumber="299"
If ($MyNumber -gt 200){
If($MyNumber -lt 300){
Write-Host "The number is above 200 and less than 300"
}
}