Terminating a script in PowerShell


I've been looking for a way to terminate a PowerShell (PS1) script when an unrecoverable error occurs within a function. For example:

function foo() {
    # Do stuff that causes an error

Of course there's no such thing as $host.Exit(). There is $host.SetShouldExit(), but this actually closes the console window, which is not what I want. What I need is something equivalent to Python's sys.exit() that will simply stop execution of the current script without further adieu.

Edit: Yeah, it's just exit. Duh.

12/1/2014 12:12:43 AM

Accepted Answer

You should use the exit keyword.

6/29/2016 8:14:39 AM

Exit will exit PowerShell too. If you wish to "break" out of just the current function or script - use Break :)

If ($Breakout -eq $true)
     Write-Host "Break Out!"
ElseIf ($Breakout -eq $false)
     Write-Host "No Breakout for you!"
    Write-Host "Breakout wasn't defined..."

Write-Error is for non-terminating errors and throw is for terminating errors

The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.

Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.

To declare a terminating error, use the Throw keyword. For more information, see about_Throw (


Terminates this process and gives the underlying operating system the specified exit code.


This will allow you to exit with a specific exit code, that can be picked up from the caller.


I think you are looking for Return instead of Break. Break is typically used for loops and only breaks from the innermost code block. Use Return to exit a function or script.


Throwing an exception will be good especially if you want to clarify the error reason:

throw "Error Message"

This will generate a terminating error.