- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use PowerShell Break statement with the While Loop?
You can use the break statement with both the While loop and the Do-While loop.
To use the Break with a while loop, see the example below.
Example
$i = 1 While($i -ne 10){ Write-Output $i if($i -eq 5){break} $i++ }
Output
1 2 3 4 5
In the above example, the loop terminates when the value of the variable $i reaches 5 because the Break statement is executed.
You can also use the break in the nested While loop, here we will take two examples of the nested loop. First when the break is placed outer loop and second when the break is placed in the inner loop.
Break statement in the Outer While loop −
Example
$i=1 $j=1 While($i -ne 10){ while($j -ne 5){ Write-Output "i = $i" Write-Output "j = $j`n" $j++ } if($i -eq 5){Break} $i++ }
Output
i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 1 j = 4
The above example is of the outer loop break. When the value of $i becomes the 5, it terminates both the while loop.
Break statement in the Inner While loop −
Example
$i=1 $j=1 While($i -ne 5){ while($j -ne 5){ Write-Output "i = $i" Write-Output "j = $j`n" if($j -eq 3){Break} $j++ } $i++ }
Output
i = 1 j = 1 i = 1 j = 2 i = 1 j = 3 i = 2 j = 3 i = 3 j = 3 i = 4 j = 3
When the value of $j becomes 3 in the above example, it terminates the child while loop and the execution move to the parent While loop and executes it.
Similarly, you can use the break statement with the Do-While loop as well as mentioned in the below example.
Break statement in the Do-While loop −
Example
$i = 1 do { Write-Output "i = $i" if($i -eq 3){Break} $i++ } while ($i -ne 5)
Output
i = 1 i = 2 i = 3
- Related Articles
- How to use PowerShell break statement with the For loop?
- How to use PowerShell break statement in foreach loop?
- How to use PowerShell Break statement with the Switch command?
- How do we use a break statement in while loop in C#?
- How to use PowerShell Break with the Label.
- How to use the break statement to come out of a loop in JavaScript?
- How to implement WHILE LOOP with IF STATEMENT MySQL?
- What is PowerShell Break statement?
- How do we use continue statement in a while loop in C#?
- How to use C# do while loop?
- How to use ‘while loop’ in Java?
- How to use the foreach loop parallelly in PowerShell?
- How to use else conditional statement with for loop in python?
- How can I use a label with break statement in JavaScript?
- How to use ‘do while loop’ in Java?
