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.

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')

See you next time with PowerShell!
Categories: PowerShell
3 replies »