Understanding break, continue, return, and exit

by Apr 27, 2015

Do you know off-hand what "break", "continue", "return", and "exit" do? These are powerful language constructs, and here is a test function to illustrate how different their effects are:

'Starting'

function Test-Function {
    $fishtank = 1..10

    Foreach ($fish in $fishtank)
    {
        if ($fish -eq 7)
        {
            break      # <- abort loop
            #continue  # <- skip just this iteration, but continue loop
            #return    # <- abort code, and continue in caller scope
            #exit      # <- abort code at caller scope 
        }

        "fishing fish #$fish"

    }
    'Done.'
}

Test-Function


'Script done!'

Simply comment out one of the keywords and run the script to see how the loop behaves.

Twitter This Tip! ReTweet this Tip!