O'Reilly logo

Windows PowerShell Quick Reference by Lee Holmes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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> }
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required