Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.
If you own the book already, login here to get free, online, searchable access to the entire book's content.
If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".
You want to control the conditions under which PowerShell executes commands or portions of your script.
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"
}
Conditional statements include the following:
if
statementExecutes the script block that follows it if its condition evaluates to true
elseif
statementExecutes 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
statementExecutes the script block that follows it if none of the conditions in the if
or elseif
statements before it evaluate to true
In addition to being useful for script control flow, conditional statements are often a useful way to assign data to a variable. PowerShell makes this very easy by letting you assign the results of a conditional statement directly to a variable:
$result
=
if
(
Get-Process
-Name
notepad
)
{
"Running"
}
else
{
"Not running"
}
For very simple conditional statements such as this, you can also use PowerShell’s ternary operator:
$result
=
(
Get-Process
-Name
notepad
*)
?
"Running"
:
"Not running"
For more information about these flow control statements, type Get-Help
about_If
.