问题
I'm using the PowerShell.Exiting engine event to save my command history and do some other tidying up when I close a PowerShell session, registering it in my profile thus:
# Set up automatic functionality on engine exit.
Register-EngineEvent PowerShell.Exiting -SupportEvent -Action `
{
#stuff
...
}
This works perfectly when I use PowerShell in a console window, but when I'm running PowerShell in ISE, it appears that the PowerShell.Exiting event somehow never fires, since nothing I put in there, be it the usual stuff or test code, ever runs.
Is this a known problem, and if so, is there a known workaround or alternative?
回答1:
Well, this is weird as hell.
After cutting down the profile completely outside the Register-EngineEvent call only to find that it still didn't work, I started to cut down the contents of that, too, and restored the rest of the profile to its original state. Here are my findings:
If you have a write-host
, or other output to the PowerShell host, in the scriptblock for Register-EngineEvent PowerShell.Exited
, it doesn't run when you exit ISE (even though it works fine when you exit the console).
In fact, none of the scriptblocks you have registered against the PowerShell.Exited event appear to run, even ones that don't contain any statements outputting to the host. (Which is why when I tested other people's working examples up above, they didn't work for me unless I started PowerShell without running the profile that added the existing event handler.)
Expunge all statements that cause host output from the scriptblocks you use with Register-EngineEvent PowerShell.Exited
, or redirect the output somewhere else, and they all start working.
(Take this with appropriate quantities of salt, since I have not yet had time to go chasing it with a debugger, but I have a sneaking suspicion ISE is closing down its tab before the engine is done with it...)
来源:https://stackoverflow.com/questions/14604596/powershell-ise-and-powershell-exiting-event