Skip to content

Instantly share code, notes, and snippets.

@karbomusic
Last active August 5, 2021 18:13
Show Gist options
  • Save karbomusic/d0893a5b4e080d0d65b63243ec93ae9e to your computer and use it in GitHub Desktop.
Save karbomusic/d0893a5b4e080d0d65b63243ec93ae9e to your computer and use it in GitHub Desktop.
Use WqlEventQuery to poll process creation, then procdump it on creation.
# Be aware of potential performance issues:
# https://docs.microsoft.com/en-us/archive/blogs/winsdk/accidental-denial-of-service-through-inefficient-program-design-part-1-watching-wmi-events-for-object-creation-e-g-win32_process
$processToWatch = "'noderunner.exe'"
# poll interval?
$timespan = [TimeSpan]::FromSeconds(1)
$whereClause = "TargetInstance ISA 'Win32_Process' and TargetInstance.Name = " + $processToWatch
$wlq = New-Object System.Management.WqlEventQuery("__InstanceCreationEvent", $timespan, $whereClause)
$watcher = New-Object System.Management.ManagementEventWatcher
$watcher.query = $wlq
# how long should we watch for the process start
$watcher.Options.Timeout = [System.TimeSpan]::FromSeconds(45)
Write-Host Waiting for process creation of $processToWatch -ForegroundColor Yellow
#blocking - if the process doesn't get created and the watcher times out - it will throw a timeout error (expected).
$e = $watcher.WaitForNextEvent();
# procdump must be in path or the same directory as the script.
if($e)
{
Write-Host Found $processToWatch ($e.TargetInstance.ProcessID) -ForegroundColor Green
Write-Host Attaching debuggger... -ForegroundColor Yellow
.\procdump -s 1, -n 3 $e.TargetInstance.ProcessID -accepteula
}
else
{
Write-Host $processToWatch did not start withing the timeout period of $watchDuration seconds, could not attach. -ForegroundColor White
}
@karbomusic
Copy link
Author

karbomusic commented Dec 2, 2020

12.2.20: Added .\ to procdump command for compatibility.
12.2.20 Added -AcceptEula to prevent cryptic PID not found error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment