Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch console close event in PowerShell?

Tags:

c#

powershell

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:

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

        ...
like image 762
Sam Porch Avatar asked Oct 07 '14 10:10

Sam Porch


People also ask

How do I get the event log in PowerShell?

The Get-EventLog cmdlet gets events and event logs from local and remote computers. By default, Get-EventLog gets logs from the local computer. To get logs from remote computers, use the ComputerName parameter. You can use the Get-EventLog parameters and property values to search for events.

Which of the following cmdlets can you use to check if the Windows event log is running?

Event logging in Windows First, there are two ways to access the events logged in Windows – through the Event Viewer and using the Get-EventLog / Get-WinEvent cmdlets. The Event Viewer is an intuitive tool which lets you find all the required info, provided you know what to look for.


1 Answers

In PowerShell use the engine event PowerShell.Exiting and specify a script blocks which process it.

Here is the example:

Register-EngineEvent PowerShell.Exiting -Action { "Exiting $(Get-Date)" >> C:\TEMP\log.txt }
like image 146
Roman Kuzmin Avatar answered Sep 28 '22 08:09

Roman Kuzmin