PowerShell/Conditions

This lesson introduces PowerShell conditions, switch statements, and regular expressions.

Objectives and Skills

edit

After completing this lesson, you will be able to:

  • Describe basic conditional statement concepts.
  • Create PowerShell scripts that use if statements.
  • Create PowerShell scripts that use switch statements.

Readings

edit
  1. Wikipedia: Conditional (computer programming)
  2. Wikipedia: Switch statement
  3. Wikipedia: Regular expression
  4. BonusBits: Mastering PowerShell Chapter 7 - Conditions

Multimedia

edit
  1. YouTube: Powershell: Learn How to Use If/Then/Else
  2. YouTube: Switch
  3. YouTube: PowerShell - How To - If Statement

Examples

edit

The if statement runs code blocks based on the results of one or more conditional tests.[1]

$tp= Read-Host 'Is it Morning (M), Afternoon (A), or Evening (E)? '
if($tp -eq 'm')
{
    Write-Output 'Good morning!'
}
elseif($tp -eq 'a')
{
    Write-Output 'Good afternoon!'
}
elseif($tp -eq 'e')
{
    Write-Output 'Good evening!'
}
else
{
    Write-Output 'Hello!'
}

Switch

edit

The switch statement checks multiple conditions for a given value and runs the corresponding code blocks.[2]

$tp = Read-Host 'Is it Morning (M), Afternoon (A), or Evening (E)? '
switch($tp)
{
    m {'Good morning!'}
    a {'Good afternoon!'}
    e {'Good evening!'}
    default {'Hello!'}
}

-Match

edit

The -match operator is used to match regular expressions. For example:[3]

$zipcode = Read-Host 'Enter zip code'
if(!($zipcode -match '^\d{5}(-\d{4})?$'))
{
    Write-Output "$zipcode is not a valid zip code."
}

Switch -Regex

edit

The switch -Regex statement checks multiple conditions for a given value based on regular expression matching and runs the corresponding code blocks.[4]

$x = Read-Host 'Enter something'
switch -Regex ($x)
{
    '.'   {'You entered a character'}
    '\d'  {'You entered a digit'}
    '\s'  {'You entered a space'}
    '\w'  {'You entered a word'}
    '\w \w' {'You entered multiple words'}
    default {'You entered nothing'}
}

Break

edit

The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.[5]

$x= Read-Host 'Enter something'
switch -Regex ($x)
{
    '^.$'
    {
        'You entered a character'
        break
    }

    '^\d$'
    {
        'You entered a digit'
        break
    }

    '^\s$'
    {
        'You entered a space'
        break
    }

    '\w \w'
    {
        'You entered multiple words'
        break
    }

    '\w'
    {
        'You entered a word'
        break
    }

    default
    {
        'You entered nothing'
    }
}

Activities

edit
  1. Review Microsoft Developer Network: Boolean Values and Operators. Create a script that uses different values and conditions to confirm that in PowerShell zero is false and anything non-zero is true. Also show that the explicit value of $false is 0 and the explicit value of $true is 1.
  2. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use an if/elseif/else statement to display their approximate age in the selected timeframe.
  3. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use an if/elseif/else statement to determine their selection and then gather the appropriate input and calculate and display the converted temperature.
  4. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use an if/elseif/else statement to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  5. Create a script that asks the user how old they are in years. Then ask the user if they would like to know how old they are in months, days, hours, or seconds. Use a switch statement to display their approximate age in the selected timeframe.
  6. Review MathsIsFun: Conversion of Temperature. Create a script that asks the user if they would like to convert Fahrenheit to Celsius or Celsius to Fahrenheit. Use a switch statement to determine their selection and then gather the appropriate input and calculate and display the converted temperature.
  7. Review MathsIsFun: Area of Plane Shapes. Create a script that asks the user what shape they would like to calculate the area for. Use a switch statement to determine their selection and then gather the appropriate input and calculate and display the area of the shape.
  8. Review Regular-Expressions: How to Find or Validate an Email Address. Create a script that uses the -match operator and a regular expression to test user input email addresses.

Lesson Summary

edit
  • Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.[6]
  • The pseudocode structure of a conditional statement is:[7]
IF (boolean condition) THEN
    (consequent)
ELSE
    (alternative)
END IF
  • If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.[8]
  • By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.[9]
  • The PowerShell syntax for a conditional statement is:[10]
if (<test1>)
    {<statement list 1>}
elseif (<test2>)
    {<statement list 2>}
else
    {<statement list 3>}
  • In PowerShell conditions, the elseif and else statements are optional.[11]
  • By default, all comparison operators (-eq, -lt, -gt, etc.) are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a "c" (-ceq, -clt, -cgt, etc.).[12]
  • In PowerShell, zero is false and anything non-zero is true. When evaluated explicitly, $false is 0 and $true is 1.[13]
  • A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.[14]
  • Switch statements come in two main variants: a structured switch which takes exactly one branch, and an unstructured switch which functions as a type of GOTO.[15]
  • PowerShell switch statements function as a hybrid between structured and unstructured, where every condition in the switch is evaluated, even after a match, but only the code block immediately following any matching condition is executed.[16]
  • The PowerShell syntax for a switch statement is:[17]
switch (<test-value>)
{
    <condition> {<statement list 1>}
    <condition> {<statement list 2>}
    ...
    default {<statement list 3>}
}
  • In PowerShell switch statements, the default case is optional.[18]
  • The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.[19]
  • A regular expression (abbreviated regex) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings.[20]
  • Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning.[21]
  • In regex, | indicates either|or.[22]
  • In regex, ? indicates there is zero or one of the preceding element.[23]
  • In regex, * indicates there is zero or more of the preceding element.[24]
  • In regex, + indicates there is one or more of the preceding element.[25]
  • In regex, () is used to group elements.[26]
  • In regex, . matches any single character.[27]
  • In regex, [] matches any single character contained within the brackets.[28]
  • In regex, [^] matches any single character not contained within the brackets.[29]
  • In regex, ^ matches the start of the string.[30]
  • In regex, $ matches the end of the string.[31]
  • In regex, \w matches a word.[32]
  • In regex, \d matches a digit.[33]
  • In regex, \s matches whitespace.[34]

Key Terms

edit
Spaghetti code
a pejorative term for source code that has a complex and tangled control structure, especially one using many GOTO statements, exceptions, threads, or other unstructured branching constructs.[35]
Structured programming
A programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops.[36]
Whitespace
Any character or series of characters that represent horizontal or vertical space.[37]

Review Questions

edit
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Conditional statements are _____.
Conditional statements are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.
2. The pseudocode structure of a conditional statement is:
The pseudocode structure of a conditional statement is:
IF (boolean condition) THEN
  (consequent)
ELSE
  (alternative)
END IF
3. If the condition is true, _____. Otherwise, the execution continues in _____.
If the condition is true, the statements following the THEN are executed. Otherwise, the execution continues in the following branch – either in the ELSE block (which is usually optional), or if there is no ELSE branch, then after the END IF.
4. By using ELSE IF/ELSEIF, it is possible to _____
By using ELSE IF/ELSEIF, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped.
5. The PowerShell syntax for a conditional statement is:
The PowerShell syntax for a conditional statement is:
if (<test1>)
  {<statement list 1>}
elseif (<test2>)
  {<statement list 2>}
else
  {<statement list 3>}
6. In PowerShell conditions, the elseif and else statements are _____.
In PowerShell conditions, the elseif and else statements are optional.
7. By default, all comparison operators (-eq, -lt, -gt, etc.) are case-_____. To make a comparison operator case-_____, _____.
By default, all comparison operators (-eq, -lt, -gt, etc.) are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a "c" (-ceq, -clt, -cgt, etc.).
8. In PowerShell, zero is _____ and anything non-zero is _____. When evaluated explicitly, $false is _____ and $true is _____.
In PowerShell, zero is false and anything non-zero is true. When evaluated explicitly, $false is 0 and $true is 1.
9. A switch statement is a _____
A switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via a multiway branch.
10. Switch statements come in two main variants: _____, and _____.
Switch statements come in two main variants: a structured switch which takes exactly one branch, and an unstructured switch which functions as a type of GOTO.
11. PowerShell switch statements function as a hybrid between structured and unstructured, where _____.
PowerShell switch statements function as a hybrid between structured and unstructured, where every condition in the switch is evaluated, even after a match, but only the code block immediately following any matching condition is executed.
12. The PowerShell syntax for a switch statement is:
The PowerShell syntax for a switch statement is:
switch (<test-value>)
{
  <condition> {<statement list 1>}
  <condition> {<statement list 2>}
  ...
  default {<statement list 3>}
}
13. In PowerShell switch statements, _____ is optional.
In PowerShell switch statements, the default case is optional.
14. The break statement _____.
The break statement immediately exits the nearest enclosing Foreach, For, While, Do, or Switch statement.
15. A regular expression (abbreviated regex) is _____.
A regular expression (abbreviated regex) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings.
16. Each character in a regular expression is either understood to be a _____, or a _____.
Each character in a regular expression is either understood to be a metacharacter with its special meaning, or a regular character with its literal meaning.
17. In regex, | indicates _____.
In regex, | indicates either|or.
18. In regex, ? indicates _____.
In regex, ? indicates there is zero or one of the preceding element.
19. In regex, * indicates _____.
In regex, * indicates there is zero or more of the preceding element.
20. In regex, + indicates _____.
In regex, + indicates there is one or more of the preceding element.
21. In regex, () is used to _____.
In regex, () is used to group elements.
22. In regex, . matches _____.
In regex, . matches any single character.
23. In regex, [] matches _____.
In regex, [] matches any single character contained within the brackets.
24. In regex, [^] matches _____.
In regex, [^] matches any single character not contained within the brackets.
25. In regex, ^ matches _____.
In regex, ^ matches the start of the string.
26. In regex, $ matches _____.
In regex, $ matches the end of the string.
27. In regex, \w matches _____.
In regex, \w matches a word.
28. In regex, \d matches _____.
In regex, \d matches a digit.
29. In regex, \s matches _____.
In regex, \s matches whitespace.

Assessments

edit

See Also

edit

References

edit
  Type classification: this is a lesson resource.
  Completion status: this resource is considered to be complete.