Wednesday, 18 May 2011

Powershell and Trapping the unexpected

Probably the most unexpected thing your script can be asked to handle is CTRL+C, when the script has been either running too long, or spawned in error. NOT!
Ok, so why is it so hard to get your script to clean up after it-self? A question very few script writers on the web have asked thus far, but acknowledged to be a source of pain. Some solution may lie in an Exception handler I thought:
    # install a handler for any exception in this method, gets called for any exceptions thrown in 
    # this function scope.
    # TODO: this trap does not always catch and kill the spawned processes, because the CTRL-C 
    #   signal handling is not supported in PoSH, unless we install a community extension which purports to do so.
    #   see :
    trap [Exception] {
        # ensure we kill off the child process to prevent zombies
        if ((!$processSpawned) -and (!$process.HasExited)) {
            Write-Host "..."
        throw $_ # rethrow the exception (implicit variable)
The Trap handler above works in general, but since the the shell appears to randomly postpone handling of CTRL-C depending on whether the process in the script that's currently running wants to do anything with the hot-key, we are missing a simple generic way to handle it. In short, it's not ideal. Questions such as this and finding their solution eventually are what make my use of Powershell in my job interesting to say the least. A mix of pragmatism is telling me to just bookmark this idea, and get back to it once this leaky bit of code proves to not be up for the job any longer.
I just want to make a note about this Trap statement block, it is not using the Continue or Break (the default conclusion to a trap is Break). And instead re-throws the exception which effectively terminates the script, but only after the really key cleanup of any zombie processes has been taken care of.
So before I run away, I'm leaving a link to a really good powershell e-book by Dr Tobias Wertner.
Disclaimer: Contrary to what you might be expecting, I am not a PoSH guru, so if you are looking for powershell help, here are two places to look for the obvious or commonly asked questions, StackOverflow, and the scripting guy blog on msdn.

No comments:

Post a Comment