PowerShell/Loops
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 | edit source]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 | edit source]- Wikipedia: Control flow
- BonusBits: Mastering PowerShell Chapter 8 - Loops
Multimedia
[edit | edit source]- YouTube: PowerShell For Loops
- YouTube: Do While Loops in PowerShell
- YouTube: ForEach Loops in PowerShell
- YouTube: PowerShell Loops
- YouTube: PowerShell - How To - Loops
Examples
[edit | edit source]While
[edit | edit source]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 | edit source]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 | edit source]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)
For
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]The Get-Counter cmdlet gets performance counter data from local and remote computers.[11]
Get-Counter
Activities
[edit | edit source]- 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.
- 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.
- 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.
- 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.
- 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.
- 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 | edit source]- 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 | edit source]- 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 | edit source]Assessments
[edit | edit source]- Flashcards: Quizlet: Windows PowerShell - Loops
- Quiz: Quizlet: Windows PowerShell - Loops
See Also
[edit | edit source]References
[edit | edit source]- ↑ Microsoft TechNet: about_While
- ↑ Microsoft TechNet: about_Do
- ↑ Microsoft TechNet: about_Do
- ↑ Microsoft TechNet: about_For
- ↑ Microsoft TechNet: about_ForEach
- ↑ Microsoft TechNet: about_Continue
- ↑ Microsoft TechNet: about_Break
- ↑ Microsoft TechNet: about_Language_Keywords
- ↑ Microsoft TechNet: ForEach-Object
- ↑ Microsoft TechNet: Using the Start-Sleep Cmdlet
- ↑ Microsoft TechNet: Get-Counter
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Wikipedia: Control flow
- ↑ Microsoft TechNet: about_Language_Keywords
- ↑ Microsoft TechNet: ForEach-Object
- ↑ Microsoft TechNet: Using the Start-Sleep Cmdlet
- ↑ Microsoft TechNet: Get-Counter
- ↑ Wikipedia: Infinite loop