Recycling IIS6 and IIS7 Application Pool With Powershell

I recently came across a need to automatically recycle an application pool.  I have a VBScript version in my archive of scripts but I’m trying to convert everything over to PowerShell.

Here’s a working PowerShell snippet that works for recycling IIS7.x application pools.  APPPOOLNAME needs to be replaced with the actual name of the application pool and SERVERNAME needs to be replaced with the NETBIOS name of the server.

$Path = “IISApplicationPool.Name=’$Name'”
Invoke-WMIMethod Recycle -Path $Path -Computer SERVERNAME -Namespace root\MicrosoftIISv2 -Authentication PacketPrivacy

That worked well in testing in my lab environment for IIS7 but not IIS6.  After some research I got the following PowerShell snippet to recycle IIS6 application pools.  Once again APPPOOLNAME needs to be replaced with the actual name of the application pool.

$appPool = get-wmiobject -namespace “root\MicrosoftIISv2” -class “IIsApplicationPool” | Where-Object {$_.Name -eq “W3SVC/APPPOOLS/APPPOOLNAME”}

So this is great, but I don’t like to maintain a separate script for each version of IIS.  The next step was to check the registry for the version of IIS and then use an if statement to execute the proper command block.  Here’s the complete script that can be run to recycle a specific application pool on an IIS6 or IIS7.x server.

##Set Server name and App Pool Name below
$Server = “SERVERNAME”
$AppPoolName = “APPPOOLNAME”
$iisVersion = Get-ItemProperty “HKLM:\software\microsoft\InetStp”;

if ($iisVersion.MajorVersion -eq 7)

$Name = “W3SVC/APPPOOLS/$AppPoolName”
$Path = “IISApplicationPool.Name=’$Name'”
Invoke-WMIMethod Recycle -Path $Path -Computer $Server -Namespace root\MicrosoftIISv2 -Authentication PacketPrivacy
$appPool = get-wmiobject -namespace “root\MicrosoftIISv2” -class “IIsApplicationPool” | Where-Object {$_.Name -eq “W3SVC/APPPOOLS/$AppPoolName”}

Rick is a Senior Support Lead at OrcsWeb, a hosted server company providing managed hosting solutions.