I want to run some code before PowerShell 2.0 window is closed. For this I tried:
PS > register-engineevent PowerShell.Exiting -action {get-process | out-file c:
The unhandled exception occurs because garbage collection has already disposed your handler by the time the unmanaged method is called. You can get around that by storing it in a static field:
private static HandlerRoutine s_rou;
public static void SetHandler()
{
if (s_rou == null)
{
s_rou = new HandlerRoutine(ConsoleCtrlCheck);
SetConsoleCtrlHandler(s_rou, true);
}
}
When you click the X to close you are closing the application hosting PowerShell. This application would need to handle the exit situation. I believe the default PS host is the Windows console which is obviously not doing what you need. You could host PowerShell in a custom host and handle the exit events. I'm on a Mac right now but maybe running under the PS ISE would handle this for you?
Unfortunately, you can't do this. The only time an exiting event will get called is if you type "exit" at the PowerShell prompt.
This is how I hook up my exiting event:
$null = Register-EngineEvent -SourceIdentifier `
([System.Management.Automation.PsEngineEvent]::Exiting) -Action { # Put code to run here }