Wednesday, January 19, 2011

Recycle IIS application pools using PowerShell

I have been working on a collection of deployment scripts for BizTalk solutions using PowerShell. One functionality is installation of services hosted in the IIS. After installation, the application pool need a restart in order to properly pick up the new/updated services.

At first, I just recycled all available application pools by the following command line

& $env:windir\system32\inetsrv\appcmd list apppools /xml | & $env:windir\system32\inetsrv\appcmd recycle apppools /in

First we list all available application pools and then we pipe this list as input into the recycle command.

While nice, it is unnecessary to recycle those application pools that are unaffected by our installation.

The main finesse in my scripts are that they are picking up all information on what to do from a configuration file. This XML file includes among other things the application pool for each service to install in IIS. Based on this I updated my recycle command to recycle each and every application pool that were specified in the configuration file. In order to not restart an application pool more than once, I pipe the foreach with sort-object and get-unique.

# List to hold the apppools
$appPools = New-Object System.Collections.ArrayList

# Loop through the objects in the xml file
# and extract the apppool name and add to the list
ForEach($wcfSetup in $xmlFile.DeployConfiguration.WcfSetups.WcfSetup)

# Recycle each unique apppool in the list
foreach($appPool in $appPools | sort-object | get-unique)
    & $env:windir\system32\inetsrv\appcmd recycle apppool /"$appPool"