Search code examples
powershellpostmortem-debuggingdebugdiag

How to post-mortem debug .NET process and run powershell script as debugger action?


Is there an easy way to monitor a given Windows process for a well defined .NET exception (either first or second chance) and run a powershell script when that exception is raised? I don't really need a process dump (yet).


Solution

  • .NET application errors are logged to the Application Events Log. In the Scheduled Task manager, we can add a task which is triggered by a .NET Runtime exception event.

    In practice, this is a bit troublesome to do by hand, since we need some additional ValueQueries to make this work, I've made a task XML which can be imported into the Task Scheduler. See this gist.

    The task needs to call our PowerShell script with an EventId, from which we retrieve the corresponding event log item, check the message for the stacktrace, and search for the matching known exception string.

    param($eventRecordID, $eventChannel = "Application")
    
    $event = Get-WinEvent -LogName $eventChannel -FilterXPath "<QueryList><Query Id='0' Path='$eventChannel'><Select Path='$eventChannel'>*[System[(EventRecordID=$eventRecordID)]]</Select></Query></QueryList>"
    
    $stackTrace = $event.Message
    
    if($stackTrace -match "ConfigurationErrorsException")
    {
        echo "Error Thrown in Application"
        # do some stuff
    }
    

    Once the task is enabled, every time your .NET application faults, the PowerShell script should be run.