Control the Application Pool

Not so long ago I needed to write a little piece of code to allow some to recycle the application from within a web application. Ok, recycling the AppPool that would be running the web application sounded a bit silly, but any other AppPool would be possible. Enter the world of WMI. Or rather, take a glimpse inside, because there’s no way this post will do justice to the power of System.Management. Here’s the little piece that I wrote, transformed into a console application.

   1:  static void ListApplicationPools(string hostname)
   2:  {
   3:  string ClassPath = @"\\" + hostname + @"\root\microsoftiisv2:IIsApplicationPoolSetting";
   4:  ManagementClass WmiObject = new ManagementClass(ClassPath);
   5:   
   6:  foreach(ManagementObject child in WmiObject.GetInstances())
   7:  {
   8:  char[] SplitChar = "/".ToCharArray();
   9:  Console.WriteLine(child.ToString().Split(SplitChar)[child.ToString().Split(SplitChar).Length-1].Replace(@"""",""));
  10:  }
  11:  }

The first method lists the application pools that are on the specified host. So you can run this method on the localhost, but also on a remote server, as long as you have administrative access to the specified host.

   1:  static void RunAppPoolCommand(string hostname, string command, string apppoolname)
   2:  {
   3:  string ClassPath = @"\\" + hostname + @"\root\microsoftiisv2:IIsApplicationPool='W3SVC/AppPools/" + apppoolname + "'";
   4:  ManagementObject WmiObject = new ManagementObject(ClassPath);
   5:   
   6:  InvokeMethodOptions Options = new InvokeMethodOptions();
   7:  Options.Timeout = new TimeSpan(0,0,10);
   8:   
   9:  ManagementBaseObject InParams = WmiObject.GetMethodParameters(command);
  10:  ManagementBaseObject OutParams = WmiObject.InvokeMethod(command, null, Options);
  11:   
  12:  if (InParams != null) InParams.Dispose();
  13:  if (OutParams != null) OutParams.Dispose();
  14:  }

The second method allows you to send commands to the specified Application Pool. These commands can be: stop, start and recycle.

You see, it’s very easy… once you know how. You can download the compiled binary here.