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);
}
...
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With