Created
March 18, 2025 18:54
-
-
Save zett42/4edd4444aea9b8422cc566779d058195 to your computer and use it in GitHub Desktop.
PowerShell Console Control Handler Demo (SetConsoleCtrlHandler)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type -TypeDefinition @' | |
using System; | |
using System.IO; | |
using System.Runtime.InteropServices; | |
public class ConsoleHelper { | |
[DllImport("Kernel32")] | |
private static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add); | |
private delegate bool HandlerRoutine(int ctrlType); | |
private static bool Handler(int ctrlType) { | |
string filePath = Path.Combine( Path.GetTempPath(), "console.log" ); | |
File.AppendAllText(filePath, "[" + DateTime.Now + "] PowerShell received control event (" + ctrlType + ")\n"); | |
return false; // Allow normal process exit | |
} | |
public static void RegisterHandler() { | |
SetConsoleCtrlHandler(new HandlerRoutine(Handler), true); | |
} | |
} | |
'@ | |
[ConsoleHelper]::RegisterHandler() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment