Guy recommends:
A free trial of
WebHelpDesk

Solarwinds Free WebHelpDesk

Install a ticket-based help desk system from SolarWinds. Download your free trial

PowerShell Continue and Break Statements

Windows PowerShell Continue Explained

PowerShell's 'Continue' statement is employed in loops where we want the script to return to the innermost loop.  I also have examples showing how the 'Break' command works.

Topics for PowerShell Continue Statement

 ♣

Example 1: Break and Continue

I have created a task, or vehicle to test 'Continue', in this scenario I want is to find words, which end in 's', in an array called $Basket.  For your information, "s$" refers to 's' in the last character of the string.

The method involves setting-up a ForEach loop, introducing 'If' and 'ElseIf' logic, and finally inserting the Continue or Break command.

Clear-Host
$Singular = $Null
$Plural = $Null
$i=0
$Basket =@("Apples","Bananas","Cherry","Plums")
ForEach ($Fruit in $Basket) {
$i++
         If ($Fruit -match "s$")
         {$Plural = $Plural + " "+ $Fruit}
#Continue
#Break
         ElseIf ($Fruit -notmatch "s$")
         {$Singular = $Singular + " "+ $Fruit}
     }
Write-Host "Plural word(s): $Plural"
Write-Host "Singular word(s) $Singular"

Testing the Script
Firstly, remove the # in front of Continue; secondly, remove the # in front of Break.  Here are the results:

#1: Original Script
# Continue
# Break
Plural word(s): Apples Bananas Plums
Singular word(s) Cherry

#2: Continue is now active
Continue
# Break
Plural word(s): Apples Bananas Plums
Singular word(s)

#3: Break is now active
# Continue
Break
Plural word(s): Apples
Singular word(s)

Learning Points 
The 'Continue' statement will trap the three fruits ending in 's', but will NOT go on to process the ElseIf statement, thus this variation misses reporting that 'Cherry' is singular.

Break will exit the loop after finding the first plural, the ElseIf is not processed, and neither are any more loops; the result is that only 'Apples' gets returned, no Bananas!

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v11.5 v11.5

SolarWinds' Network Performance Monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM now.

Download a free trial of Solarwinds' Network Performance Monitor

Example 2: Mission to Find Prime Numbers

Guy's crazy logic - possibly; could do better - almost certainly.  Shows the benefit of PowerShell's 'Continue' statement - definitely.

This example contains two loops.  The outer loop, $Range contains an array of numbers to check.  I calculated the upper limit by raising the largest number in the range (Maximum) to the power of 2, [Math]::pow.

$Known contains an array of known prime numbers, in the course of a loop 'If' tests each $Range number by divided $Item by a prime.  If the % (Modulo) is not zero, then that means there is a remainder.  At this point in the script 'Continue' plays its part and returns to beginning of the inner loop, without adding that number to the AntiPrime list.

$AntiPrime contains a list of all those numbers that cannot be prime numbers.  Next, using Compare-Object we can use a type of subtraction to generate the list of actual PrimeNumbers.  Well I warned you - Guy's crazy logic!

# Calculate prime numbers.  Features PowerShell Continue statement.
Clear-Host
$Known = @(2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101)
$Range = 1..[math]::pow(($Known | Measure-Object -Maximum).Maximum,2)
$AntiPrime = @()
$Result =@()
$Filter =$Null
ForEach ($Item in $Range){
     Foreach ($Num in $Known) {
         If($Item % $Num -ne 0){Continue; }
         $AntiPrime += $Item
     } # End of inner $Known loop
} # End of outer $Range loop
Clear-host
# Section to calculate prime numbers
$Primus = Compare-Object -ReferenceObject $AntiPrime -DifferenceObject $Range |
Where {$_.SideIndicator -match "=>"}
ForEach ($X in $Primus) {$Result = $Result + $X.InputObject}
$PrimeNumbers = $Result + $Known | Sort-Object | Out-Host
"`n Biggest number tested: " + [math]::pow(($Known | Measure-Object -Max).Maximum,2)
" Prime numbers detected: " + ($PrimeNumbers = $Result + $Known).count

Note 1: Check the effect of removing the word Continue.

Note 2: Much to my surprise, the script generates a list of prime numbers if I replace Continue with Break.

Note 3: Naturally, I am working on ways to improve this script, both in writing tighter code, and in highlighting Continue and Break.

Research PowerShell's Continue and Break

As often, the built-in help files have interesting detail about a command.  Although Continue seems like a keyword, PowerShell documentation refers to it as a statement.  See more with:

Clear-Host
Get-Help about_Break -full

Note 4: Actually, PowerShell's about_Break file was more interesting than the about_Confirm offering.  Incidentally, PowerShell has a keyword called 'Return' which is a useful alternative for some scripts.

See more about PowerShell's Loops ยป

Summary of PowerShell Continue Statement

PowerShell's 'Continue' statement is useful when you want particular results from loops.  It's sister command is 'Break', this returns to the start of the loop with even less processing.  Both statements have specialist roles, and help to achieve just the output you want.

If you like this page then please share it with your friends

 


See more Windows PowerShell flow control examples

PowerShell Switch Statement  • PowerShell Real-life Techniques  • Free Permissions Analyzer

Differences between For, ForEach and ForEach-Object  • PowerShell Loops  • PowerShell Home

Conditional Operators   • Do While Loop  • PowerShell If Statement  • PowerShell Brackets

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

 

 *


Custom Search

Site Home

Guy Recommends: WMI Monitor for PowershellSolarwinds WMI Monitor

Windows Management Instrumentation (WMI) is most useful for PowerShell scripting.

SolarWinds have produced this Free WMI Monitor to take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

Author: Guy Thomas Copyright © 1999-2017 Computer Performance LTD All rights reserved.

Please report a broken link, or an error to: