Do You Use "Break"?

"Break" is a special keyword that you can use to exit loops and conditions prematurely. Have a look:

Do {
$pwd = Read-Host 'Enter your password'
If ($pwd -eq 'topsecret') { break }
} While ($true)

As such, the loop would run endless. Its exit condition is an embedded condition that calls break when appropriate. Of course, you could have placed your exit condition after While as well, but break allows you to be more flexible and have multiple exit conditions at various code positions.

Twitter This Tip! ReTweet this Tip!


Posted Oct 13 2010, 08:00 AM by ps1

Comments

Carsten Schwartz wrote re: Do You Use "Break"?
on 10-13-2010 1:48 PM

Oh yes!

break is a classic as well as continue for usage in for loops to skip execution of the code block and  continue with the next iteration.

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.