Terminating a script in PowerShell

Viewed 1215734

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.

11 Answers

May be it is better to use "trap". A PowerShell trap specifies a codeblock to run when a terminating or error occurs. Type

Get-Help about_trap

to learn more about the trap statement.

I thought up a neat little trick to do just that, when I wanted a function to exit a script without throwing an error, but not exit the console if the function was used from there. It involves the $PSScriptRoot automatic variable that is only defined when running a script.

if($PSScriptRoot){exit}
Related