tags:

views:

187

answers:

1

I'm looking for a way to automatically do some clean up tasks when the PowerShell session quits. So for example in my profile file I start a process which needs to run in the background for quite a lot of tasks and I would like to automatically close that process when I close the console.

Is there some function the PowerShell automatically calls when closing the session as it does with prompt when displaying the prompt?

+3  A: 

There is the Register-EngineEvent cmdlet which you can use to attach an event handler to the Exiting event:

Register-EngineEvent PowerShell.Exiting –Action { ... }

Note however, that this event will not be fired if you close the console window.

Joey
Thanks, that works fine but I mostly close my shell without typing `exit` explicitely. Maybe someone else has an idea, otherwise I need to get used to the `exit` ;)
poke
Btw. you should add the parameter `-SupportEvent` to prevent PowerShell from printing out the event data whenever the shell starts. -- Or pipe it to `Out-Null`.
poke
@poke: I'm using the following little snippet in my profile: `Invoke-Expression "function $([char]4) { exit }"` this allows me to exit PowerShell by pressing Ctrl+D and Enter. Not perfect but short enough to avoid going for the X button.
Joey
Whoah, that's a nice idea! Thank you very much :)
poke