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);
}
}