How do I catch the console close event in PowerShell?

How do I catch the console close event in PowerShell?

I tried to add a console management handler and it works fine for CMD but not in PowerShell, is there any other way in PowerShell?

Example:

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

        ...

      

+3


source to share


1 answer


In PowerShell, use the PowerShell.Exiting event and specify the script blocks that handle it.

Here's an example:



Register-EngineEvent PowerShell.Exiting -Action { "Exiting $(Get-Date)" >> C:\TEMP\log.txt }

      

+4


source







All Articles