Conditional Statements
Conditional statements in PowerShell allow you to change the flow of execution in your script.
if, elseIf, and else Statements
if(condition){ <statement block> } elseif(condition2) { <statement block> } else { <statement block> }
If condition evaluates to $true, then PowerShell executes the
statement block you provide. Then, it resumes execution at the end of
the if / elseif / else statement list. PowerShell requires the
enclosing braces around the statement block even if the statement
block contains only one statement.
Tip
See the sections “Logical Operators” and “Comparison Operators” for a discussion on how PowerShell evaluates expressions as conditions.
If condition evaluates to $false, then PowerShell evaluates any
following (optional) elseif
conditions until one matches. If one matches, PowerShell executes the
statement block associated with that condition, then resumes execution
at the end of the if / elseif / else statement list.
If none of the conditions evaluate to $true, then PowerShell executes the
statement block associated with the (optional) else clause, then resumes execution at the
end of the if / elseif / else statement list.
switch Statements
switch [options] (expression) { <comparison value> { <statement block> } -or- { expression } { <statement block> } (…) default { <statement block> } }
or:
switch [options] –file <filename> { <comparison value> { <statement block> } -or- { expression } { <statement block> } (…) default { <statement block> } }
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access