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:
PS C:\> for($a=1; $a -lt 10; $a++)
>> {
>> if ($a -eq 6)
>> {
>> break
>> }
>> echo $a
>> }
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:
PS C:\> $array="windows","Linux","MacOS","Android"
PS C:\> foreach ($os in $array) {
>> if ($os -eq "MacOS") {
>> break
>> }
>> echo $os }
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:
PS C:\> $num = 2
PS C:\> switch($num)
>> {
>> 1{ echo "value is equal to 1"}
>> 2{ echo " value is equal to 2" ; break }
>> 3{ echo " value is equal to 3" ; break }
>> 2{ echo " value is equal to 2" ; break }
>> }
Output:value is equal to 2
Leave a Reply