Sometimes you want to divide conditions into some block statements, to do that, we're going to use powerShell if statement. Here condition will be evaluated and return boolean value true or false.
If (condition) {
statement(s)
statement(s)
}
To get more understanding in this tutorial it's better to know about comparison operator. Let's take a look some examples what you can do with if statement.
if ($a -eq 10) {
Write-Host "$a is equal with 10."
}
$a = 20
if ($a -gt 10) {
Write-Host "$a is greater thatn 10."
}
If you have two condition, you can use if else statement.
If (condition)
statement(s)
else
statement(s)
As the block statement getting more complex, you can use elseif statement.
If (condition)
statement(s)
elseif (condition)
statement(s)
else
statement(s)
You can also nested the condition.
If (condition)
statement(s)
else
statement(s)
$a = 10
if ($a -eq 10) {
Write-Host "$a is equal with 10."
} else {
Write-Host "$a is not equal with 10."
}
As the block statement getting more complex, you can use elseif statement.
If (condition)
statement(s)
elseif (condition)
statement(s)
else
statement(s)
$a = 10
if ($a -gt 10) {
Write-Host "$a is greater than 10."
} elseif ($a -lt 10) {
Write-Host "$a is less than 10."
} else {
Write-Host "$a is equal with 10."
}
You can also nested the condition.
$a = 31
if ($a -gt 0) {
if ($a % 2 -eq 0) {
Write-Host "$a is positive and even number."
} else {
Write-Host "$a is positive and odd number."
}
} else {
if ($a % 2 -eq 0) {
Write-Host "$a is negative and even number."
} else {
Write-Host "$a is negative and odd number."
}
}
0 Response to "PowerShell If Statement"
Post a Comment