PowerShell: If/Then/Else (Flow Control)

By Xah Lee. Date: . Last updated: .

if statement

if (3 -gt 2) { echo "yes" }

if else:

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

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

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

if elseif else chain:

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

if expression

if expression returns a value.

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

PowerShell Operators


PowerShell in Depth

Path

Pipe

Comment

Value Types

String

Variable

Boolean

Conditional

Data Structure

Loop and Iteration

Input/Output

Function

Profile and Script

Script Examples

Misc