PowerShell Conditional logic if, else and else if


Example

Powershell supports standard conditional logic operators, much like many programming languages. These allow certain functions or commands to be run under particular circumstances.

With an if the commands inside the brackets ({}) are only executed if the conditions inside the if(()) are met

$test = "test"
if ($test -eq "test"){
    Write-Host "if condition met"
}

You can also do an else. Here the else commands are executed if the if conditions are not met:

$test = "test"
if ($test -eq "test2"){
    Write-Host "if condition met"
}
else{
    Write-Host "if condition not met"
}

or an elseif. An else if runs the commands if the if conditions are not met and the elseif conditions are met:

$test = "test"
if ($test -eq "test2"){
    Write-Host "if condition met"
}
elseif ($test -eq "test"){
    Write-Host "ifelse condition met"
}

Note the above use -eq(equality) CmdLet and not = or == as many other languages do for equlaity.