"Continue" and Labels

by May 18, 2015

When you use the "Continue" statement inside a loop, you can skip the remainder of this loop iteration, and continue with the next. "Break" works similar, but aborts a loop and skips all remaining iterations.

This raises the question which loop is affected when you use nested loops. By default, "Continue" targets the inner loop, but by using labels, you can point both "Continue" and "Break" to outer loops as well.

:outer 
Foreach ($element in (1..10))
{
  for ($x = 1000 $x -lt 1500 $x += 100) 
  {
    "Frequency $x Hz"
    [Console]::Beep($x, 500)
    continue outer
    Write-Host 'I am never seen unless you change the code...'
  }
}

Since the sample code continues with the outer loop, you see (and hear) 10 times a 1000Hz output.

When you remove the "outer" label following "Continue", you will get beeps in increasing frequency, and the Write-Host statement is no longer skipped.

Twitter This Tip! ReTweet this Tip!