PowerShell

PowerShell: Difference between the Break and Throw Statement

If you are a PowerShell scripter, you may have come across two code statements that are not unique to PowerShell: Break and Throw. In this blog post I will carry out some examples to shed some light on this very important statements.

Break

Break statements causes PowerShell to immediately exit the loop. The most important thing here is to keep in mind that break only exits the loop that is currently processed.

I have prepared a short example for better understanding. Here it is.


do {

$q=Read-Host "Enter your name or press Q to quit"

do {

$a=Read-Host "Enter your age or press Q to quit"

If ($a -ge '100')

{break}

}

until ($a -eq 'Q')

}

until ($q -eq 'Q')

In Line 11 a break statement appears. That break statement will cause the second loop to exit if you enter an age greater than 100. However, it will not exit the entire script. We will be still in there, namely in the first loop that asks for our name.

Anmerkung 2020-04-05 110555.png

Throw or in other words Game Over

Unlike break, throw will terminate the entire script. It’s easy, if the condition is met,  game over ;-). Note that a message can be given. In my case it’s “Error”. So, throw supports user input which is represented as an error message.


do {

$q=Read-Host "Enter your name or press Q to quit"

do {

$a=Read-Host "Enter your age or press Q to quit"

If ($a -ge '100')

{throw "Error"}

}

until ($a -eq 'Q')

}

until ($q -eq 'Q')

Anmerkung 2020-04-05 111403.png

See you next time with PowerShell!

Categories: PowerShell

Tagged as: ,

3 replies »

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.