« Previous 1 2
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" } }
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.
« Previous 1 2
Buy this article as PDF
(incl. VAT)