Skip to content

Instantly share code, notes, and snippets.

@zett42
Created March 18, 2025 18:54
Show Gist options
  • Save zett42/4edd4444aea9b8422cc566779d058195 to your computer and use it in GitHub Desktop.
Save zett42/4edd4444aea9b8422cc566779d058195 to your computer and use it in GitHub Desktop.
PowerShell Console Control Handler Demo (SetConsoleCtrlHandler)
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