Conditionals
Powershell doesn't have an 'else if' keyword, must nest if statements inside else blocks:
Clear-Host
$var = 2
if ($var -eq 1)
{
Clear-Host
"If branch"
}
else
{
Clear-Host
"Else branch"
if ($var -eq 2)
{
"If -eq 2 branch"
}
else
{
"Else else branch"
}
}
Switch-case:
Clear-Host
$var = 42
switch ($var)
{
41 {"Forty One"}
42 {"Forty Two"}
43 {"Forty Three"}
default {"Something else"}
}
Will match all lines that are -eq:
# Outputs 'Forty Two' and 'Forty Two String'
Clear-Host
$var = 42
switch ($var)
{
42 {"Forty Two"}
"42" {"Forty Two String"}
default {"Something else"}
}
To avoid matching multiple cases, use break:
# Outputs only 'Forty Two'
Clear-Host
$var = 42
switch ($var)
{
42 {"Forty Two"; break}
"42" {"Forty Two String"}
default {"Something else"}
}
Switch also works with collections:
# Matches each case one at a time
Clear-Host
switch (3, 1, 2, 42)
{
1 {"One"}
2 {"Two"}
3 {"Three"}
default {"Something else"}
}
Switch is case insensitive by default, use -casesensitive to change this:
# Will only output 'mixedcase', without -casesensitive would match all 3 cases
Clear-Host
switch -casesensitive ("Pluralsight")
{
"pluralsight" {"lowercase"}
"PLURALSIGHT" {"uppercase"}
"Pluralsight" {"mixedcase"}
}
Also supports wildcards using the -Wildcard switch:
# Matches all 3 cases
Clear-Host
switch -Wildcard ("Pluralsight")
{
"plural*" {"*"}
"?luralsight" {"?"}
"Pluralsi???" {"???"}
}