PowerShell for Windows Admins

Mar 19 2014   8:33AM GMT

Give me a break

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Having shown how to use continue last time I thought I’d show the opposite functionality this time and demonstrate how to jump out of a loop.

You do this using the break command.  The following examples show how it works. What do you think the output of these loops will be?

FOR loop

for ($i=1; $i -le 6; $i++){   if ($i -eq 4) {break}   $i }

WHILE loop

$i = 0 while ($i -lt 6){ $i++ if ($i -eq 4) {break} $i

DO loop

$i = 0 do { $i++ if ($i -eq 4) {break} $i } while ($i -lt 6)

$i = 0 do { $i++ if ($i -eq 4) {break} $i } until ($i -ge 6)


$numbers = 1..6 foreach ($number in $numbers) { if ($number -eq 4) {break} $number }

If you said the output would be




You were correct.


1..6 | foreach { if ($psitem -eq 4) {break} $psitem }

Though you want to think carefully before terminating a pipeline like this.

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: