Skip to main content

Adjust Script Flow Using Conditional Statements in Windows PowerShell

Problem

You want to control the conditions under which PowerShell executes commands or portions of your script.

Solution

Use PowerShell’s if, elseif, and else conditional statements to control the flow of execution in your script.

For example:

$temperature = 90

if($temperature le 0)

{

"Balmy Canadian Summer" } elseif($temperature le 32) {

"Freezing" } elseif($temperature le 50) {

"Cold" } elseif($temperature le 70) {

"Warm" } else {

"Hot" }

Discussion

Conditional statements include the following:

if statement Executes the script block that follows it if its condition evaluates to true

elseif statement Executes the script block that follows it if its condition evaluates to true, and none of the conditions in the if or elseif statements before it evaluate to true

else statement Executes the script block that follows it if none of the conditions in the if or elseif statements before it evaluate to true

For more information about these flow control statements, type GetHelp About_ Flow_Control. Automate PowerShell scripts using conditional statements on a United Kingdom Dedicated Server, providing dedicated resources, reliable performance, and full administrative control for efficiently managing automated server-side tasks.

Help Category