Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

A tiny Utility to recycle an IIS Application Pool


:P
On this page:

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

Posted in IIS7  .NET  Windows  

The Voices of Reason


 

Mike Chaliy
October 02, 2012

# re: A tiny Utility to recycle an IIS Application Pool

Using powershell

Import-Module WebAdministration
Restart-WebAppPool WestWindArticles

Cyril DURAND
October 02, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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

Arjan
October 02, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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

Slava
October 02, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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
}
}

Trevor
October 02, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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

Fred Morrison
October 02, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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)
}

Rick Strahl
October 03, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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 :-)

Steve Schofield
October 04, 2012

# re: A tiny Utility to recycle an IIS Application Pool

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. :)

Rick Strahl
October 04, 2012

# re: A tiny Utility to recycle an IIS Application Pool

@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...

Jeff
June 12, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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

Rick Strahl
June 20, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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.

KM
June 28, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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?

Rick Strahl
June 28, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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...

KM
June 29, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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.

Rick Strahl
June 29, 2013

# re: A tiny Utility to recycle an IIS Application Pool

@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.

KM
July 01, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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.

Midhun
November 15, 2013

# re: A tiny Utility to recycle an IIS Application Pool

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?

Graham
April 26, 2014

# re: A tiny Utility to recycle an IIS Application Pool

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!

Vignesh
June 26, 2017

# re: A tiny Utility to recycle an IIS Application Pool

I'm trying to recycle an app pool hosted in a IIS 7.5 server (local to the code). I wrote the same code (in VB.NET) but it throws an "Unknown error (0x80005000)". Did you encounter a similar error? The only other interesting thing about my code is that its wrapped up in a Windows Service Application. The service keeps running and invokes the code to recycle the app pool every 60 secs (for testing sake). Is there anything that's wrong about what I'm doing here?


Rick Strahl
June 26, 2017

# re: A tiny Utility to recycle an IIS Application Pool

@vignesh - most likely you need to be an administrator and you have to have the IIS 6 Metabase compability tools installed.


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