Javatpoint Logo
Javatpoint Logo

Continue and Break Statement

Continue Statement

The Continue statement is used in PowerShell to return the flow of the program to the top of an innermost loop. This statement is controlled by the for, Foreach and while loop.

When this statement is executed in a loop, the execution of code inside that loop following the continue statement will be skipped, and the next iteration of a loop will begin. It is generally used for a condition so that a user can skip some code for a specific condition.

Examples

Example 1: The following example displays the number from 1 to 10 but not 5 using continue statement in while loop:

Output:

1
2
3
4
6
7
8
9
10

The Value 5 is missing in the output because when the value of variable $a is 5 if condition is true and the continue statement encountered after the increment of the variable, which makes the control to jump at the beginning of the while loop for next iteration, skipping the statements for current iteration so that's why the echo command will not execute for the current iteration.

Example 2: The following example uses a do-while loop with a continue statement which displays the values from 10 to 20, excluding 15 and 18.

Output:

10
11
12
13
14
16
17
19
20

Example 3: The following example uses for loop with continue statement:

Output:

10
9
8
7
6
4
3
2
1

Break Statement

The Break statement is used in PowerShell to exit the loop immediately. It can also be used to stop the execution of a script when it is used outside the switch or loop statement.

Examples

Example 1: The following example displays how to use a break statement to exit a 'for' loop:

Output:

1
2
3
4
5

In this example, the break statement exit the 'for' loop when the value of the variable $a is 6.

Example 2: The following example displays how to use a break statement to exit a 'foreach' loop:

Output:

Windows
Linux

In this example, the Foreach statement iterates the values of an array $array. Each time the code block is executed. The 'If' statement evaluates to False for first two times and the value of the variable displays on the PowerShell. On the third time, the loop is executed but the value of the variable $array equals the string "MacOS". At this point, the Break statement executes, and the Foreach loop exits.

Example 3: The following example displays how to use a break statement to exit a switch statement:

Output:

value is equal to 2

Next TopicPowerShell String




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA