Advertisement
Advertisement


Terminating a script in PowerShell


Question

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
    $host.Exit()
}

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.

2014/12/01
1
410
12/1/2014 12:12:43 AM

Accepted Answer

You should use the exit keyword.

2016/06/29
406
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!"
     Break
}
ElseIf ($Breakout -eq $false)
{
     Write-Host "No Breakout for you!"
}
Else
{
    Write-Host "Breakout wasn't defined..."
}
2014/12/01

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 (http://go.microsoft.com/fwlink/?LinkID=145153).

2020/06/20

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

https://msdn.microsoft.com/en-us/library/system.environment.exit%28v=vs.110%29.aspx

[Environment]::Exit(1)

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

2015/02/25

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.

2013/05/06

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

throw "Error Message"

This will generate a terminating error.

2014/12/01

Source: https://stackoverflow.com/questions/2022326
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]