PowerShell: If Then Else (Flow Control)

By Xah Lee. Date: . Last updated: .

if statement

if (3 -gt 2) { Write-Host "yes" }

if else:

if (3 -gt 4) { Write-Host "yes" } else { Write-Host "no" }

multiple statements needs to be placed on separate lines, or with semicolon at the end.

if (3 -gt 4) { Write-Host "yes" } else {
Write-Host "no" ;
Write-Host "wrong";
 }

if elseif else chain:

$x = 9;
if ($x -eq 1) {Write-Host "is 1"}
elseif ($x -eq 2) {Write-Host "is 2"}
else {Write-Host "is other"}

if expression

if expression returns a value.

$y = ( 9 -gt 5 ? "red" : "green")
# $y is now green

PowerShell, Boolean Related