Lets briefly describle the usage of Powershell IF statement.
If you had any prior experience with programming languages like C, Java etc, it follows the same flow in PowerShell too.
We would start with some handy compare operators that we could use along with the IF condition.
general syntax of IF usage.
If ($this -eq $that) {
# commands
} elseif ($those -ne $them) {
# commands
} elseif ($we -gt $they) {
# commands
} else {
# commands
}
A sample to try using the IF statement.
Example 1
$Status=(Get-service -name bits).status
If ($Status -eq "Running")
{
Write-Output "Service is being stopped"
Stop-Service -name bits
}
Else
{
Write-Output "Service is already stopped"
}
Example 2 : Simple IF
if ($a -gt 5)
{
Write-Host "The value $a is greater than 5."
}
Example 3 : Simple IF & ELSE
if ($a -gt 5)
{
Write-Host "The value $a is greater than 5."
}
else
{
Write-Host "The value $a is less than or equal to 5"
}
Example 4 : Simple IF, ELSE & ELSEIF
if ($a -gt 5)
{
Write-Host "The value $a is greater than 5."
}
elseif ($a -eq 5)
{
Write-Host "The value $a is equal to 5."
}
else
{
Write-Host "The value $a is less than 5"
}
We could try the below comparison operators while using IF condition.
Comparison Operators
The following operators are all Case-Insensitive by default:
-eq Equal
-ne Not equal
-ge Greater than or equal
-gt Greater than
-lt Less than
-le Less than or equal
-like Wildcard comparison
-notlike Wildcard comparison
-match Regular expression comparison
-notmatch Regular expression comparison
-replace Replace operator
-contains Containment operator
-notcontains Containment operator
-Happy Scripting...