Contact   •   Products   •   Search

Rick Strahl's Web Log

Wind, waves, code and everything in between...
ASP.NET • C# • HTML5 • JavaScript • AngularJs

A tiny Utility to recycle an IIS Application Pool


In the last few weeks I've annoyingly been having problems with an area on my Web site. It's basically ancient articles that are using ASP classic pages and for reasons unknown ASP classic locks up on these pages frequently. It's not an individual page, but ALL ASP classic pages lock up. Ah yes, gotta old tech gone bad. It's not super critical since the content is really old, but still a hassle since it's linked content that still gets quite a bit of traffic. When it happens all ASP classic in that AppPool dies. I've been having a hard time tracking this one down - I suspect an errant COM object

I have a Web Monitor running on the server that's checking for failures and while the monitor can detect the failures when the timeouts occur, I didn't have a good way to just restart that particular application pool. I started putzing around with PowerShell, but - as so often seems the case - I can never get the PowerShell syntax right - I just don't use it enough and have to dig out cheat sheets etc. In any case, after about 20 minutes of that I decided to just create a small .NET Console Application that does the trick instead, and in a few minutes I had this:

using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;

namespace RecycleApplicationPool
{
    class Program
    {

        static void Main(string[] args)
        {
            string appPoolName = "DefaultAppPool";
            string machineName = "LOCALHOST";
            if (args.Length > 0)
                appPoolName = args[0];
            if (args.Length > 1)
                machineName = args[1];

            string error = null;

            DirectoryEntry root = null;
            try
            {
                Console.WriteLine("Restarting Application Pool " + appPoolName + " on " + machineName + "...");
                root = new DirectoryEntry("IIS://" + machineName + "/W3SVC/AppPools/" +appPoolName);
                Console.WriteLine(root.InvokeGet("Name"));
                root.Invoke("Recycle");                
                Console.WriteLine("Application Pool recycling complete...");

            }
            catch(Exception ex)
            {
                error = "Error: Unable to access AppPool: " + ex.Message;                
            }

            
            if ( !string.IsNullOrEmpty(error) )
            {
                Console.WriteLine(error);
                return;
            }
        }
    }
}

To run in you basically provide the name of the ApplicationPool and optionally a machine name if it's not on the local box.

RecyleApplicationPool.exe "WestWindArticles"

And off it goes. What's nice about AppPool recycling versus doing a full IISRESET is that it only affects the AppPool, and more importantly AppPool recycles happen in a staggered fashion - the existing instance isn't shut down immediately until requests finish while a new instance is fired up to handle new requests.

So, now I can easily plug this Executable into my West Wind Web Monitor as an action to take when the site is not responding or timing out which is a big improvement than hanging for an unspecified amount of time.

I'm posting this fairly trivial bit of code just in case somebody (maybe myself a few months down the road) is searching for ApplicationPool recyling code. It's clearly trivial, but I've written batch files for this a bunch of times before and actually having a small utility around without having to worry whether Powershell is installed and configured right is actually an improvement. Next time I think about using PowerShell remind me that it's just easier to just build a small .NET Console app, 'k? :-)

Resources

Make Donation
Posted in IIS7  .NET  Windows  


Feedback for this Post

 
# re: A tiny Utility to recycle an IIS Application Pool
by Mike Chaliy October 02, 2012 @ 4:11am
Using powershell

Import-Module WebAdministration
Restart-WebAppPool WestWindArticles
# re: A tiny Utility to recycle an IIS Application Pool
by Cyril DURAND October 02, 2012 @ 4:57am
Hi Rick,

For information, there is command line to recycle appPool.

Starting with IIS7, we could use the appcmd command line :
c:\windows\system32\inetsrv\appcmd recycle apppool "MyAppPool"

With IIS6, I thing iisapp.vbs script will help.
If you need to manage remote server, you could use psExec from sysinternals : http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx

Cyril DURAND
# re: A tiny Utility to recycle an IIS Application Pool
by Arjan October 02, 2012 @ 5:04am
I think the Restart-WebAppPool cmdlet from the iis webadministration powershell module will do the same.
http://technet.microsoft.com/en-us/library/ee790580.aspx
# re: A tiny Utility to recycle an IIS Application Pool
by Slava October 02, 2012 @ 5:44am
Still, it should be more convenient to do such tasks with Powershell. I use next functions below to start and stop app pool, it could be used also for recycling purpose, or there might be even dedicated API for recycling (just lazy to google it):

function Stop-AppPool($poolName)
{
$poolPath = "IIS:\AppPools\" + $poolName
if(Test-Path $poolPath)
{
Stop-WebItem $poolPath -errorAction SilentlyContinue | Wait-Process
}
}

function Start-AppPool($poolName)
{
if(Test-Path ("IIS:\AppPools\" + $poolName))
{
# Start-WebItem doesn't work
Start-WebAppPool $poolName
"$poolPath started" | Out-Host
}
}
# re: A tiny Utility to recycle an IIS Application Pool
by Trevor October 02, 2012 @ 6:30am
You might want to have a look at Tess Ferrandez's Windbg tutorials if you actually want to track down what's going on. http://blogs.msdn.com/b/tess/archive/2008/02/04/net-debugging-demos-information-and-setup-instructions.aspx
# re: A tiny Utility to recycle an IIS Application Pool
by Fred Morrison October 02, 2012 @ 11:33am
Alternatively, in PowerShell:
# Purpose: recycles the IIS app pool with the specified partial name
# Author: Fred Morrison
param([string] $appPoolPartialName='Default')
$appPool = Get-WmiObject -Namespace "root\MicrosoftIISv2" -Class "IIsApplicationPool" | Where-Object {$_.Name -like "W3SVC/AppPools/*$appPoolPartialName*"}
if($appPool -ne $null)
{
$appPool.Recycle()
Write-Host ('Successfully recycled application pool {0} on server {1}' -f $appPool.Name,$appPool.__SERVER)
}
# re: A tiny Utility to recycle an IIS Application Pool
by Rick Strahl October 03, 2012 @ 4:19pm
Ah I love my blog - I knew I could count on getting tons of responses on how to do it in Powershell :-) Just looking at the syntax makes my skin crawl though :-)
# re: A tiny Utility to recycle an IIS Application Pool
by Steve Schofield October 04, 2012 @ 5:20pm
Why not capture a memory dump and try to see if you can track the issue down? Or isolate the content in a separate app pool. I agree the powershell syntax takes a bit of messing around, although in Win8 has a code wizard generator. :)
# re: A tiny Utility to recycle an IIS Application Pool
by Rick Strahl October 04, 2012 @ 7:11pm
@Steve - the interesting thing is that the worker process actually doesn't die - only all ASP classic code dies. So it appears that the ASP processing engine locks up - everything else in the app pool keeps on running just fine (ASP.NET, static content etc.)... I don't even know what I would be looking for a in a memory dump. The main issue is that there are no apparent errors either - nothing in the event logs, no failure messages of any kind because for all intents and purposes the IIS monitoring service thinks everything's fine.

I suspect it's one of my ancient COM objects, but I thought I had removed all references of those from ASP pages. Going back to looking...
# re: A tiny Utility to recycle an IIS Application Pool
by Jeff June 12, 2013 @ 1:34pm
Hi, thanks for posting the small app... It works nicely, except it is requiring I hit a key or manually close the window. Is there a way to suppress this?

Thanks again.

J
# re: A tiny Utility to recycle an IIS Application Pool
by Rick Strahl June 20, 2013 @ 12:00am
J - it's not in the code. If you run this in Visual Studio's debugger it'll keep the console window open, but the actual app run from the command window won't wait for user input.
# re: A tiny Utility to recycle an IIS Application Pool
by KM June 28, 2013 @ 3:19pm
When I try and compile, I get:

The type or namespace name 'DirectoryServices' does not exist in the namespace 'System' (are you missing an assembly reference?)

for line 4:

using System.DirectoryServices;

Any ideas?
# re: A tiny Utility to recycle an IIS Application Pool
by Rick Strahl June 28, 2013 @ 4:22pm
There should a be a reference in the project for System.DirectoryServices. If it's not there you need to add it, but I checked here locally and I have it in there...
# re: A tiny Utility to recycle an IIS Application Pool
by KM June 29, 2013 @ 9:34am
Many thanks! I thought I had added the reference, but it was missing.

Is anyone running this on IIS 8? It seems to lack permissions to run. I am logged in and also running the script as an administrator (for now) and have also given myself permission to "log on as a service" in the local policy administrator. But it does not see to be recycling the app pool when I check in Event Log --> Custom Views --> Server Roles --> Web Server (IIS). I see the app pool recycling there, but only every 30 minutes (exactly), not when this app is run.
# re: A tiny Utility to recycle an IIS Application Pool
by Rick Strahl June 29, 2013 @ 11:59am
@KM - You have to make sure the IIS6 Management Tools are installed for IIS 8. It's in the install options and yes I run it on my Windows 8 machine.
# re: A tiny Utility to recycle an IIS Application Pool
by KM July 01, 2013 @ 8:43pm
Thanks again. I figured out that the events were not all being logged in Event Viewer.

To fix this I selected the application pool I wanted to recycle, and then clicked on Advanced Settings in the right menu. I expanded Generate Recycle Event Log Entry and then changed Manual Recycle and Specific Time to True. Now I see the recycles from this app in the log.

I was attempting to get a .vbs script working that ran great under Windows Server 2008, but it was not working at all in WS 2012. I kept getting "permissions are insufficient" errors, even though I was logged in as an Admin. It appears that I had the permissions wrong for the .vbs script, or possibly it is not longer supported in Windows Server 2012 (or not as easy to implement).

This is a great app, and saved the day for me. Very useful. Thanks for sharing.
# re: A tiny Utility to recycle an IIS Application Pool
by Midhun November 15, 2013 @ 2:57am
Hi All,

I have seen all your posts. I have recycled application pools using directory services successfully using

root = new DirectoryEntry("IIS:// Localhost/W3SVC/AppPools/" +appPoolName);
this is to recycle app pools in localhost.

but i need to recycle application pools present on other machine from my machine.

I am able to get list of all app pools of other machine from my machine and even status of a particular app pool. the only thing is that i am unable to perform (recycle,start,stop)

Anyone have any idea?
# re: A tiny Utility to recycle an IIS Application Pool
by Graham April 26, 2014 @ 2:07pm
Great utility - thanks for sharing. We've been having persistent, intermittent errors with Crystal Reports for Visual Studio. The code works flawlessly but then the CR engine will choke on itself for a variety of reasons. Recycling the App Pool is quick and easy and fixes the problems. Now I can have my key users run this app whenever a CR report fails. Thanks again!
 


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2014