Let me provide some background information, to complement your own answer:
PowerShell scripts typically run until they finish, but it can be useful to build in a mechanism for the script to terminate gracefully after completing its intended tasks.
Exiting a Text-Based Script
If your script is text-based, adding a termination mechanism is super simple. Just using the command in PowerShell will prompt the script to terminate.
For example, suppose that you had a script containing these commands:
Write-Host ‘Line 1’Write-Host ‘Line 2’ExitWrite-Host ‘Line 3’
The script would display the phrases “Line 1” and “Line 2”, but it would never display “Line 3” because the exit command causes the script to terminate before it ever reaches the “Line 3” command.
The last line of code does not execute because the script terminates before reaching that point.
Here is what the code used to create such a prompt might look like:
Exiting a GUI-Based Script
As you can see, terminating a text-based script is simple – just insert the Exit command at the desired termination point. However, let’s look at how you can terminate a
Here is the source code for a simple GUI-based script:
This script displays the words within a GUI interface. The only thing that makes it different from any other Hello World script that you might have seen before is that the GUI also contains an exit button, as shown in Figure 3.
This simple Hello World script contains an exit button.
At a functional level, this script is straightforward and works just like any other PowerShell GUI-based script. I began by loading the necessary assemblies. From there, I created a form object, a label object (the Hello World text), and a button object. Then, I told PowerShell to add the label object and the button object to the form and to display the form.
So, now that I have outlined how the script works, let’s examine the exit button. Whenever you create a button object in PowerShell, you have the option of associating a click action with the button. Here are the commands associated with the click action:
Escape Key Termination
The third line tells PowerShell what to do if the escape key is pressed. Once again, we are going to close the form.
As you can see, there are any number of different ways that you can gracefully terminate a PowerShell script. The technique that you use largely depends on whether the script is text-based or GUI-based.
About the Author(s)
Brien Posey is a bestselling technology author, a speaker, and a 20X Microsoft MVP. In addition to his ongoing work in IT, Posey has spent the last several years training as a commercial astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space.

Understanding the need for breaking and exiting loops
Before diving into the techniques, it is important to understand why you might need to break or exit a loop. There could be several scenarios where you want to terminate a loop before it reaches its natural endpoint. For example, you may encounter an unexpected condition that requires immediate action, or you may have achieved the desired result and want to stop further iteration. By breaking or exiting loops when necessary, you can gain more control over your code execution.
The PowerShell break command

A loop, essentially, is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Now, there may be circumstances where you’d want to interrupt that cycle and stop the script right in its tracks. That’s where ‘break’ comes into play. The break
command in PowerShell allows you to terminate a loop prematurely, regardless of how many items are left to iterate over in the collection. It can be used with different types of loops, such as for
, while
, and foreach
. Let’s explore how to use the break
command with each type of loop.
Breaking a for loop in PowerShell
To break out of a for
loop in PowerShell, you can use the break
command. Here’s an example:
for ($i = 1; $i -le 10; $i++) { if ($i -eq 5) { break } Write-Host "Iteration $i" }
In this example, when the value of $i
becomes 5, the break
statement is executed, causing the loop to terminate immediately. The output will be:
Iteration 1 Iteration 2 Iteration 3 Iteration 4

Breaking a while loop in PowerShell
Similar to the for
loop, you can use the break
command to exit a while
loop. The break
command will immediately terminate the loop when executed. Here’s an example:
$i = 1 while ($i -le 10) { if ($i -eq 5) { break } Write-Host "Iteration $i" $i++ }
In this example, the loop will iterate from 1 to 4, and then terminate when $i
becomes 5. The output will be:
Iteration 1 Iteration 2 Iteration 3 Iteration 4
Break and Exiting the ForEach loop in PowerShell
In PowerShell, the foreach
loop is used to iterate over a collection of items. To exit a foreach
loop prematurely, you can use the break
command. Let’s see how it works.
# PowerShell break foreach loop - example $fruits = @("apple", "banana", "cherry", "date") foreach ($fruit in $fruits) { if ($fruit -eq "cherry") { break } Write-Host $fruit } Write-Host "Loop exited"
In this example, the foreach
loop will iterate over the $fruits
array. When it encounters the “cherry” item, the break
command is executed, causing the loop to terminate immediately. The output will be:
The line Write-Host "Loop exited"
is executed after the loop is exited prematurely.

Choosing the appropriate moment to utilize the ‘break’ command is crucial. In a scenario where you’re searching for a particular item within an array or a set of files in a directory, once you’ve located your target, it’s needless to proceed with the remaining items. Consequently, implementing the ‘break’ statement optimizes your code, saves time, and enhances efficiency.
You can use the “break” statement to exit any other loops like Do-Until, Do-while loop, etc., in PowerShell. Here is an example:
$i = 1 do { if ($i -eq 5) { break } Write-Output $i $i++ } while ($i -le 10)
The break
command stops the current loop iteration and continues with the next command in the script.
The Continue Statement
In contrast to ‘break’, another beneficial keyword, ‘continue’, makes PowerShell skip to the next iteration of the loop. While ‘break’ entirely terminates the loop, ‘continue’ only halts the current iteration and proceeds to the next one. Here is an example:
# Loop through numbers 1 to 10 for ($i = 1; $i -le 10; $i++) { # If the number is 4, skip the rest of the loop iteration using "continue" if ($i -eq 4) { Write-Output "Skipping number 4" continue } # If the number is 7, exit the loop entirely using "break" if ($i -eq 7) { Write-Output "Breaking on number 7" break } # Otherwise, display the number Write-Output $i }
When $i is 4, the message “Skipping number 4” is displayed, and the number 4 isn’t printed because of the continue statement. When $i is 7, the message “Breaking on number 7” is displayed, and the loop exits immediately due to the break statement, so numbers 8, 9, and 10 are not processed. Here is the output:
1 2 3 Skipping number 4 5 6 Breaking on number 7
Here, the “continue” Causes the loop to skip the rest of the current iteration and move directly to the next iteration. The “break” Exits the loop immediately, regardless of the loop’s terminating condition.
Tips and best practices for breaking and exiting loops in PowerShell
Breaking and exiting loops in PowerShell can sometimes be tricky, especially when dealing with nested loops or complex conditions. Here are some tips and best practices to keep in mind:
- Understand the Scope: The break statement will only exit the innermost loop that it is currently inside. If you have nested loops and you use a
break
statement inside the inner loop, only the inner loop will be exited – the outer loops will continue to execute. - Use with Caution: While break can be useful in controlling the flow of your program, excessive use of
break
can make your code harder to read and understand. Try to design your loops so that the exit condition is part of the loop structure itself (i.e., as part of thewhile
orfor
condition) rather than relying onbreak
. - Combine with Conditional Statements: The
break
statement is often used in conjunction with anif
statement to test a certain condition. Be sure that your conditional logic is correct before breaking out of a loop, to avoid unexpected program behavior. - Don’t Forget about
continue
: Whilebreak
is used to completely exit a loop, thecontinue
statement is used to skip the rest of the current iteration and move on to the next one. This can sometimes be a better option if you only want to skip specific iterations rather than exiting the loop entirely. - Comment Your Code: If you use
break
to exit a loop when a certain condition is met, make sure to clearly comment this in your code. This will help others (and you, when you come back to your code later) understand why thebreak
is there and what condition it’s checking for. - Testing and Debugging: Make sure to thoroughly test your code when using
break
to ensure that it is working as expected. Consider all possible cases and make sure your loop behaves correctly.
Wrapping up
Now that you have a comprehensive understanding of breaking and exiting loops in PowerShell, it’s time to put your knowledge into practice. Remember, though, with great power comes great responsibility – use it judiciously, and your scripts will be more efficient and effective than ever. Happy scripting!
What is the purpose of the break statement in PowerShell?
The break
statement in PowerShell is used to exit a loop prematurely. It allows you to immediately stop the execution of a loop and continue with the next statement after the loop.
How do I use the break statement in a loop?
Can the break statement be used in different types of loops?
Yes, the break
statement can be used in various types of loops in PowerShell, including foreach
, for
, while
, and do-while
loops.
How does break differ from exit in PowerShell?
break
is specifically used to exit loops, while exit
is used to exit the entire script or function. break
allows you to exit a loop early without completing all iterations, while exit
terminates the entire script execution.
Can I use the break statement in a switch statement?
Is there a way to break out of a script or function in PowerShell?
To exit a function, you can use the return
keyword. The exit
command is used to exit the entire script or function.
The PowerShell build runner is specifically designed to run PowerShell scripts.
The plugin responsible for PowerShell integration has been open-sourced on GitHub.
Cross-Platform PowerShell
Cross-platform PowerShell (PowerShell Core) is supported on Windows, macOS, and Linux: download a PowerShell package for your platform and install it on the TeamCity agent.
Side-by-side installation of PowerShell Desktop and PowerShell Core is supported under Windows.
Detection of Installed PowerShell on Build Agents
During the startup, a TeamCity agent searches for the PowerShell installation in standard locations, such as Program Files
and Windows
directories, or ~/powershell
and /opt/microsoft/powershell/<version>/
in ARM64 systems. You can specify a custom location in the teamcity.powershell.detector.search.paths
agent property, so the agent can detect PowerShell in this directory (and its children) as well.
To list multiple locations, separate their paths with ;
.
PowerShell Settings
List of PowerShell versions supported by TeamCity. It is passed to | |
PowerShell run mode | Select the desired execution mode on a x64 machine: Specify a version (for example, 1.0 or 2.0). It will be compared to the version installed on the agent, and an appropriate requirement will be added. For Core editions, it will be used as the lower bound. On Desktop editions, the exact version will be used ( If the version field is left blank, no lower bound on the version requirement will be added, no Select the platform bitness:
Select a PowerShell edition to be used:
|
Format stderr output as: | Specify how the error output is handled by the runner:
|
Specify the path to the build working directory. | |
Select whether you want to enter the script right in TeamCity, or specify a path to the script:
| |
Script execution mode | Specify the PowerShell script execution mode. By default, PowerShell may not allow execution of arbitrary The |
Available if “Script execution mode” option is set to “Execute .ps1 script from external file”. | |
Additional command line parameters | Specify parameters to be passed to the PowerShell executable. |
Docker Settings
In this section, you can specify the Docker image which will be used to run the build step.
Current Limitations
Execution under Docker requires the PowerShell executable to be added to PATH.
When using Docker to run the build step, only Docker-related build agent requirements are applied to the build.
Selection of Edition in PowerShell build step affects the executable being used (
powershell.exe
for Desktop,pwsh
for Core).<Auto> defaults to
pwsh
(Core).To specify a custom PowerShell executable, the
teamcity.powershell.virtual.executable
configuration parameter must be set to the full path of this executable inside the provided image.Current limitations of the Container Wrapper do not allow Linux containers running under Windows systems.
Known Issues
If the
docker-compose
command is run via PowerShell Desktop version 5.1.17763 or later, the PowerShell script could potentially fail with an error despite having only false positive warnings in the build log.
To work around this problem, we suggest using PowerShell Core instead. Alternatively, you can limit the logging level for thedocker-compose
command by adding the--log-level ERROR
attribute to it.
Interaction with TeamCity
Attention must be paid when using PowerShell to interact with TeamCity through service messages. PowerShell tends to wrap strings written to the console with commands like Write-Output
, Write-Error
and similar (see TW-15080). To avoid this behavior, either use the Write-Host
command, or adjust the buffer length manually:
Error Handling
Due to the PowerShell issue that causes zero exit code to be always returned to a caller, TeamCity cannot always detect whether the script has executed correctly or not. We recommend several approaches that can help in detecting script execution failures:
Manually catching exceptions and explicitly returning exit code
The PowerShell plugin does not use the cmd wrapper aroundpowershell.exe
. It makes returning the explicit exit code possible.Setting to and adding a build failure condition:
In case syntax errors and exceptions are present, PowerShell writes them tostderr
. To make TeamCity fail the build, set Error Output option toError
and add a build failure condition that will fail the build on any error output.Failing build on certain message in build log:
Add a build failure condition that will fail the build on a certain message (say “POWERSHELL ERROR”) in the build log.
Handling Output
To properly handle non-ASCII output from PowerShell, the correct encoding must be set both on the PowerShell side and on the TeamCity side.
To set the encoding on the TeamCity agent side, either set the Java launch option
-Dfile.encoding=UTF-8
, or set the build configuration parameterteamcity.runner.commandline.stdstreams.encoding
value toUTF-8
.
Temporary Files
The TeamCity PowerShell plugin uses temporary files as an entry point; these files are created in the build temporary directory and removed after the PowerShell build step is finished. To keep the files, set the powershell.keep.generated
or teamcity.dont.delete.temp.files
configuration parameter to true
.
Development Links
The PowerShell support is implemented as an open-source plugin. For development links refer to the plugin’s page.
Last modified: 19 September 2023