This lesson introduces PowerShell loops, including condition-based while and do while/do until loops, counter-based for loops, and collection-based foreach loops.

Objectives and Skills

edit

After completing this lesson, you will be able to:

  • Describe basic loop statement concepts.
  • Create PowerShell scripts that use while and do loops.
  • Create PowerShell scripts that use for loops.
  • Create PowerShell scripts using foreach loops.

Readings

edit
  1. Wikipedia: Control flow
  2. BonusBits: Mastering PowerShell Chapter 8 - Loops

Multimedia

edit
  1. YouTube: PowerShell For Loops
  2. YouTube: Do While Loops in PowerShell
  3. YouTube: ForEach Loops in PowerShell
  4. YouTube: PowerShell Loops
  5. YouTube: PowerShell - How To - Loops

Examples

edit

While

edit

The while statement runs a statement list zero or more times based on the results of a conditional test.[1]

$i = 0
while($i -lt 3)
{
    Write-Output $i
    $i++
}

Do While

edit

The do while statement runs a statement list one or more times based on the affirmative results of a conditional test.[2]

$i = 0
do
{
    Write-Output $i
    $i++
}while($i -lt 3)

It is important to note that, unlike while, a do while or do until will always execute at least once.

$i = 0
do
{
    Write-Output $i
    $i--
}while($i -gt 0)

Do Until

edit

The do until statement runs a statement list one or more times based on the negative results of a conditional test.[3]

$i = 0
do
{
    Write-Output $i
    $i++
}until($i -ge 3)

The for statement runs a statement list zero or more times based on an initial setting, a conditional test, and a repeated statement, most often used with numeric counters.[4]

for($i = 0; $i -lt 11; $i++)
{
    Write-Output $i
}

For loops are often nested to repeat actions, such as for rows and columns. For example:

for($i = 0; $i -lt 3; $i++)
{
    $line = ''
    for($j = 0; $j -lt 3; $j++)
    {
        $line += $i.ToString() + $j.ToString() + '  '
    }
    Write-Output $line
}

ForEach

edit

The foreach statement runs a statement list once for each item in a collection.[5]

$processes = Get-Process
foreach($process in $processes)
{
    if($process.PM / 1024 / 1024 -gt 100)
    {
        Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
    }
}

Continue

edit

The continue statement immediately returns script flow to the top of the innermost While, Do, For, or ForEach loop.[6]

$processes = Get-Process
foreach($process in $processes)
{
    if($process.PM / 1024 / 1024 -le 100)
    {
        continue
    }
    Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
}

Break

edit

The break statement causes Windows PowerShell to immediately exit the innermost While, Do, For, or ForEach loop or Switch code block.[7]

$processes = Get-Process
foreach($process in $processes)
{
    if($process.PM / 1024 / 1024 -gt 100)
    {
        Write-Output ('Process ' + $process.Name + ' is using more than 100 MB RAM.')
        break
    }
}

Exit

edit

Exit causes Windows PowerShell to exit a script or a Windows PowerShell instance.[8]

if(<some fatal error>)
{
    Exit <optional return code>
}

Foreach-Object

edit

The ForEach-Object cmdlet runs a command list once for each item in a collection.[9] While the ForEach-Object cmdlet is often more convenient, the foreach statement and a coded loop usually offers better performance.

Get-Process | ForEach-Object { if($_.PM / 1024 / 1024 -gt 100) {'Process ' + $_.Name + ' is using more than 100 MB RAM.'} }

Start-Sleep

edit

The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time.[10] It is particularly useful with long-running scripts or infinite loops.

while($true)
{
    if((Get-Date -Format 'hh:mm') -eq '00:00')
    {
        'It''s midnight.  You should go to sleep.'
    }
    Start-Sleep -Seconds 60
}

Get-Counter

edit

The Get-Counter cmdlet gets performance counter data from local and remote computers.[11]

Get-Counter

Activities

edit
  1. Create a script that asks the user to enter grade scores. Start by asking the user how many scores they would like to enter. Then use a loop to request each score and add it to a total. Finally, calculate and display the average for the entered scores. Revise the script several times to compare the code required when the loop control structure is based on while, do while, do until, and for statements, respectively.
  2. Review MathsIsFun: 10x Printable Multiplication Table. Create a script that uses nested for loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values.
  3. Review MathsIsFun: 10x Printable Multiplication Table. Create a script that uses nested for loops to generate a multiplication table. Use a condition with (<variable> % 2) to test for odd or even values. Generate the multiplication table only for even values. For odd values, use the continue statement to continue the next iteration of the loop.
  4. Review MathsIsFun: 10x Printable Multiplication Table. Create a script that uses nested for loops to generate a multiplication table. Rather than simply creating a 10 by 10 table, ask the user to enter the starting and ending values. Use a break statement to terminate the loop if the count exceeds 10.
  5. Create a script that retrieves a list of all services and then uses foreach to display the names of all running services. While this could also be done using Select-Object, there are times when processing objects is faster and easier using foreach.
  6. Review Microsoft TechNet: Using the Start-Sleep Cmdlet. Write a script that uses an infinite loop to call the Get-Counter cmdlet every sixty seconds. Redirect the Get-Counter output and append it to a file. Run the script for a few minutes and then check the file contents to observe system utilization.

Lesson Summary

edit
  • Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.[12]
  • Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.[13]
  • PowerShell does not support an unconditional branch. All control flow must be structured using conditions, loops, functions (subroutines), or exit (unconditional halt).
  • PowerShell uses curly braces to designate code blocks and control structures.[14]
  • A loop is a sequence of statements which is specified once but which may be carried out several times in succession.[15]
  • Loop structures include while and do while/do until, for, and foreach.[16]
  • While and do while/do until are condition-controlled loops, repeating until some condition changes.[17]
  • For loops are count-controlled loops, repeating a certain number of times.[18]
  • Foreach loops are collection-controlled loops repeating for all elements of an array, or all members of a set or collection.[19]
  • Loops may be continued prematurely using the continue statement.[20]
  • Loops may be terminated prematurely using the break statement.[21]
  • Scripts may be terminated prematurely using the exit statement.[22]
  • The ForEach-Object cmdlet runs a command list once for each item in a collection.[23]
  • The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time.[24]
  • The Get-Counter cmdlet gets performance counter data from local and remote computers.[25]

Key Terms

edit
infinite loop
A sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over.[26]

Review Questions

edit
Enable JavaScript to hide answers.
Click on a question to see the answer.
1. Control flow refers to _____.
Control flow refers to the order in which the individual statements, instructions or function calls of an imperative or a declarative program are executed or evaluated.
2. Control flow statement types include _____, _____, _____, _____, and _____.
Control flow statement types include unconditional branch, conditional branch, conditional loop, subroutines, and unconditional halt.
3. PowerShell does not support _____. All control flow must be structured using _____, _____, _____, or _____.
PowerShell does not support an unconditional branch. All control flow must be structured using conditions, loops, functions (subroutines), or exit (unconditional halt).
4. PowerShell uses curly braces to _____.
PowerShell uses curly braces to designate code blocks and control structures.
5. A loop is _____.
A loop is a sequence of statements which is specified once but which may be carried out several times in succession.
6. Loop structures include _____ and _____, _____, and _____.
Loop structures include while and do while/do until, for, and foreach.
7. While and do while/do until are _____.
While and do while/do until are condition-controlled loops, repeating until some condition changes.
8. For loops are _____.
For loops are count-controlled loops, repeating a certain number of times.
9. Foreach loops are _____.
Foreach loops are collection-controlled loops repeating for all elements of an array, or all members of a set or collection.
10. Loops may be continued prematurely using _____.
Loops may be continued prematurely using the continue statement.
11. Loops may be terminated prematurely using _____.
Loops may be terminated prematurely using the break statement.
12. Scripts may be terminated prematurely using _____.
Scripts may be terminated prematurely using the exit statement.
13. The ForEach-Object cmdlet _____.
The ForEach-Object cmdlet runs a command list once for each item in a collection.
14. The Start-Sleep cmdlet _____.
The Start-Sleep cmdlet allows you to pause Windows PowerShell activity for a specified period of time.
15. The Get-Counter cmdlet _____.
The Get-Counter cmdlet gets performance counter data from local and remote computers.

Assessments

edit

See Also

edit

References

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