Question:
How do I catch the console close event in PowerShell?
I’ve tried adding a console control handler, and it works fine for CMD, but not in PowerShell, is there a different way in PowerShell?
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
namespace Test_ConCtrl { class Program { public enum CtrlTypes : uint { CTRL_C = 0, ... } public delegate Boolean ConsoleCtrl_Delegate(CtrlTypes CtrlType); [DllImport("kernel32.dll")] static extern bool SetConsoleCtrlHandler( ConsoleCtrl_Delegate HandlerRoutine, bool Add); public static Boolean My_CtrlHandler(CtrlTypes inConType) { switch(inConType) { ... } } static void Add_Handler() { ConsoleCtrl_Delegate myHandler = My_CtrlHandler; SetConsoleCtrlHandler(myHandler, true); } ... |
Answer:
In PowerShell use the engine event PowerShell.Exiting and specify a script blocks which process it.
Here is the example:
1 2 |
Register-EngineEvent PowerShell.Exiting -Action { "Exiting $(Get-Date)" >> C:\TEMP\log.txt } |