Nearly everything you might do has a condition.
For instance, if it’s cold outside, you might wear a coat.
Every language has conditionals.
In PowerShell, as in many languages, a conditional is represented by the keyword “if”.
if ($ItsColdOutside)
{
"I just can't stay"
}
Coniditionals are a basic part of programming. As in if you don’t learn conditionals, you’ll never learn to code.
In PowerShell, If will be followed by a condition (in parenthesis), and an action (in curly braces).
Coniditionals wouldn’t be too much use if you could only handle one condition.
So, PowerShell (and almost every language), if can be followed by an else keyword.
if ($ItsColdOutside)
{
"I just can't stay"
}
else
{
"I can stay"
}
Coniditionals also wouldn’t be much use if you could only handle two conditions, either.
In a given if, you can have as many elseif conditions as you’d like.
if ($ItsColdOutside)
{
"I just can't stay"
}
elseif ($My.Friends -notcontains 'You')
{
"I won't stay"
}
elseif ($My.Friends -contains 'You')
{
"I could stay"
}
else
{
"I can stay"
}
If isn’t the only conditional in PowerShell (or most languages).
PowerShell also has a switch keyword.
A switch is followed by an expression. We switch what we do based off of the output of the expression.
Let’s start simple:
$temperature = 32
switch ($temperature) {
32 { "It's Freezing (in Fahrenheit)" }
0 { "It's Freezing (in Celsius)" }
}
Switch statements can get a lot more complicated than that, of course.
You should keep reading your trust PowerShell Guide, or consult the about topics.