Give me a break

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)

FOREACH loop

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

If you said the output would be

1

2

3

You were correct.

THIS NEXT ONE WILL WORK

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

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

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s