PowerShell ISE and PowerShell.Exiting event

I'm using the PowerShell.Exiting event to save command history and do some other things when I close my PowerShell session by registering it in my profile like this:

# Set up automatic functionality on engine exit.
Register-EngineEvent PowerShell.Exiting -SupportEvent -Action `
{
    #stuff
    ...
}

      

This works great when I use PowerShell in the console window, but when I run PowerShell in ISE it seems that the PowerShell.Exiting event somehow never fires since nothing I put there, be it regular stuff or test code ever launched.

This is a known issue, and if so, is there a known workaround or alternative?

0


source to share


1 answer


Well, this is weird as hell.

After slicing the profile completely outside of the Register-EngineEvent call, only to find that it was still not working, I began to trim its contents as well and restore the rest of the profile to its original state. Here are my findings:

If you have write-host

or other output to the PowerShell host, in the scriptblock for Register-EngineEvent PowerShell.Exited

it does not run when exiting ISE (even if it works fine when exiting the console).



In fact, none of the script blocks you registered for the PowerShell.Exited event are fired, even those that don't contain any statements being output to the host. (This is why, when I tested other people working on the examples above, they didn't work for me unless I started PowerShell without starting the profile that added the existing event handler.)

Change any statements that cause node output from scripts you use with Register-EngineEvent PowerShell.Exited

, or redirect output somewhere else, and they all start working.

(Take this with the appropriate amounts of salt, since I haven't had time to chase it with the debugger yet, but I have a suspicious suspicion that ISE closes its tab before the engine is done with it ...)

+3


source







All Articles