tags:

views:

90

answers:

2

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.

+4  A: 

What about the 'Exit' command?

Michael Bray
Holy crap, if I wasn't so caught up trying to figure out how to do these things cleverly I would've probably tried that to begin with and figured out it works :) Thanks.
kprobst
+1  A: 

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.

fpschultze