// apdebug.js // // This script takes an app pool name on the command line, iterates the running // instances of w3wp.exe, and then launches the JIT debugger with a command line // that instructs it to attach to the process that's hosting the specified // app pool. // // Mike Woodring // Bear Canyon Consulting LLC // http://www.bearcanyon.com // http://www.pluralsight.com/mike // // Parse/validate the command line (a single app pool name argument is required). // var targetAppPool = (WScript.Arguments.Length == 1 ? WScript.Arguments(0) : null); if( targetAppPool == null ) { WScript.Echo("You must specify an app pool name on the command line."); WScript.Quit(); } // Enumerate the running instances of w3wp.exe. // var wmi = GetObject("winmgmts://./root/cimv2"); var w3wpInstances = wmi.ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'w3wp.exe'"); if( w3wpInstances.Count == 0) { WScript.Echo("No running instances of w3wp.exe found."); WScript.Quit(); } // Setup a regular expression that can parse the -ap command line switch // for an instance of w3wp.exe. VBScript's regex support doesn't include // named capture, but it does support capturing groups which can be referred // to by index. // var regexp = /-ap\s+\"([^.]+)\"/i; // Iterate over the collection of w3wp.exe processes identified above, // using the regex to extract the contents of the -ap (app pool) // command line option. // WScript.Echo("Active app pools..."); var targetPID = 0; var targetAppPoolLowerCase = targetAppPool.toLowerCase(); var enumerator = new Enumerator(w3wpInstances); for( enumerator.moveFirst(); !enumerator.atEnd(); enumerator.moveNext() ) { var w3wp = enumerator.item(); var matches = regexp.exec(w3wp.CommandLine); if( matches.length == 2 ) { // Successfully parsed the -ap command line for the running // instance of w3wp.exe being operated on. Perform a case-insensitive // string comparison of that app pool name with the app pool name // passed to this script's command line. If we've found a match, // make a note of this w3wp's process ID (and original-case app pool name). // var appPoolName = matches[1]; WScript.Echo(" " + appPoolName + " (" + w3wp.ProcessId + ")"); if( appPoolName.toLowerCase() == targetAppPoolLowerCase ) { // This is instances of w3wp.exe we want to attach the // debugger to. So make a note. // targetPID = w3wp.ProcessId; targetAppPool = appPoolName; } } } WScript.Echo(); if( targetPID != 0 ) { // Found it - debug it. // WScript.Echo("Launching debugger for '" + targetAppPool + "' (" + targetPID + ")..."); var vsjitCommandLine = "vsjitdebugger -p " + targetPID; var shell = WScript.CreateObject("WScript.Shell"); shell.Run(vsjitCommandLine, 1, false); } else { WScript.Echo("The app pool specified (" + targetAppPool + ") is not running."); }