Features of PowerShell loops

Say Again?

Loop Exit: The continue and break Statements

In some scripts it can be useful, and sometimes necessary in terms of the program logic, to break out of the loop and its execution at some point. PowerShell provides for this scenario with the continue and break instructions. The following example shows their use in a foreach loop:

foreach ($file in Dir $env:windir) {
  if ($file -isnot [System.IO.FileInfo]) { continue }
  "@File {0} has a size of {1} bytes." -f $file.name,$file.length
}

This loop iterates through the Windows system directory (usually C:\Windows) and uses an if condition to test whether the object given to it is a file (Figure 3). If not, the continue statement is executed and the next iteration is triggered. Program execution jumps back to the loop head and reads the next object. To completely exit a loop, you can use the break statement. We can use the while loop example shown earlier; however, we have changed it to a genuine infinite loop by starting with the while ($true) condition (which is always true):

while ($true) {
$input= Read-Host "Please enter"
if ($input -eq "secret") {
Write-Host "exactly"
break }
else{
Write-Host "wrong" }
}
Figure 3: The continue statement jumps back to the head of the loop – so that subsequent statements are not executed – and thus to the next iteration, provided the if condition is true.

After prompting and getting the input, the secret password is queried again using an if statement and then compared using the -eq operator. If it is the same, the script returns the corresponding message and breaks out of the loop, thanks to the break statement. If it is not true, the else branch with the negative message is traversed and the loop starts again from the beginning.

Conclusions

PowerShell loops can simplify automation significantly in IT operations with very little use of resources. In this article, we have given you an overview of the various loop constructs and statements in PowerShell.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus