Multiple conditions to evaluate is sometimes necessary in
order to decide whether the script should continue to execute a specific
command or do another process.
PowerShell is able to do this kind of task using if else statement.
Example script below just shows 3 variables that should match and it will
output "OK", the output is just a write-host command but it could be replaced with other codes.
And if one of the statements does not match the "else" statement is
executed.
Example code: All statements or
condition matches
$var1="Online"
$var2="Running"
$var3="Proceed"
if (($var1 -eq "Online") -and ($var2 -eq "Running") -and ($var3 -eq "Proceed"))
{
write-host "OK"
} else {
write-host "Not OK unable to Proceed"
}
Output: OK
One of the variable does not match:
$var1="Online"
$var2="Running"
$var3="Do not proceed"
if (($var1 -eq "Online") -and ($var2 -eq "Running") -and ($var3 -eq "Proceed"))
{
write-host "OK"
} else {
write-host "Not OK unable to Proceed"
}
Output: Not OK unable to Proceed
The code can be tweaked to match only two variables to proceed, the
other variable would just be optional.
Requires only two variable matches and will display OK, requires either $var1 or $var2 to match and $var3 is the other second variable that is required to match.
$var1="Offline"
$var2="Running"
$var3="Proceed"
if (($var1 -eq "Online") -or ($var2 -eq "Running") -and ($var3 -eq "Proceed") )
{
write-host "OK"
} else {
write-host "Not OK unable to Proceed"
}
Output: OK
$var1="Online"
$var2="Stopped"
$var3="Proceed"
if (($var1 -eq "Online") -or ($var2 -eq "Running") -and ($var3 -eq "Proceed"))
{
write-host "OK"
} else {
write-host "Not OK unable to Proceed"
}
$var1="Offline"
$var2="Stopped"
$var3="Proceed"
if (($var1 -eq "Online") -or ($var2 -eq "Running") -and ($var3 -eq "Proceed") )
{
write-host "OK"
} else {
write-host "Not OK unable to Proceed"
}
Output: Not OK unable to Proceed
Since either $var1 and $var2 matches.
The if statement is being evaluated from left
to right, so the order on how the variables are written on the if statement
matters, if the “-or” statement is at the last place so only 1 statement needs
to match and the “OK” statement will be executed.
if (($var1 -eq "Online") -and ($var3 -eq "Proceed") -or ($var2 -eq "Running"))
The statement above will ignore the “-and” statement and as long as the “-or”
statement matches, the “OK” statement will be executed and the “else”
will be ignore.
Cheers...till next time.
================================
Heaven's Dew Fall Prayer app for Android :
https://play.google.com/store/apps/details?id=com.myrosaryapp
Comments
Post a Comment