break and continue loops

You have now learned about the basics of the loops, but you might have asked yourself: is it possible to skip some loops or to just break the looping process? For this purpose, there are the keywords break and continue. The continue keyword will just skip the current statement and jump to the looping header or footer for the next loop. The break keyword will jump completely out of the looping process and start executing the code after the loop. Let's take a look at a simple example:

# simple example for break in a do-while loop
$a = 0
do
{
$a++
$a
if ($a -gt 2)
{
break;
}
}
while ($a -lt 5)
# 1, 2, 3

As you can see, we have just added an additional if condition, which executes the break statement after the third execution of the statement. Therefore, we only get the numbers 1-3 returned. The next example shows the usage of the continue keyword:

# simple example for a continue in a foreach-loop
$stringArray = 'Pow', 'er','Shell', 42
foreach ($obj in $stringArray)
{
if ($obj -like '*er*')
{
continue;
}
Write-Host $obj
}
# 'Pow', 'Shell', '42'

In this example, we have also added an additional condition, which validates if the $obj variable text is like '*er*'. It executes the continue keyword and skips the current loop iteration in this case. This causes the erstring value to be skipped, and therefore, not returned.

Avoid using break and continue outside of loops, as it may create some unexpected behaviour.

Further information can be found in the following links:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.199.243