Flush the SharePoint Configuration Cache

From time to time you may need to flush the SharePoint configuration cache on servers within your farm, my colleague Joe Rodgers blogged about this many moons ago - http://blogs.msdn.com/b/josrod/archive/2007/12/12/clear-the-sharepoint-configuration-cache-for-timer-job-and-psconfig-errors.aspx. If you run into a scenario that you need to flush the configuration cache on all servers within a farm this can become a very boring and laborious job.

I wrote the following script which will work with MOSS 2007, SharePoint 2010 and SharePoint 2013, simply execute from one server within the farm and the script will perform a configuration cache flush on all servers within the farm.

$ErrorActionPreference = "Stop"
#Load SharePoint assembly
$Assemblies = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Retrieve SharePoint servers
$Farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$SPServers = $Farm.Servers | Where {$_.Role -eq "Application"} | Foreach {$_.Name}

#Detect if running on MOSS 2007 and set the appropriate name for the service
If (Test-Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12")
Else {
    $Timer = "SPTimerV4"


If ([Environment]::OSVersion.Version.Major -lt 6)
$Folder = "Documents and Settings\All Users\Application Data\Microsoft\SharePoint\Config"
$Folder = "programdata\Microsoft\SharePoint\Config"

#Loop through each server
Foreach ($Server in $SPServers)
Try {
    #Stop the Timer Service
    Write-Host "-Stopping the Timer Service on $Server" -ForegroundColor Green
    $A = (Get-WmiObject Win32_Service -filter "name='$Timer'" -ComputerName $Server).StopService()
    While ($B = (Get-WmiObject Win32_Service -filter "name='$Timer'" -ComputerName $Server).State -ne "Stopped")
            Start-Sleep 5

    #Clear the Config Cache
    Write-Host "-Clearing the Config Cache on $Server" -ForegroundColor Green
    $ConfigCache = Get-ChildItem \\$Server\c$\$Folder | Sort LastWriteTime | Select -last 1
    $ConfigCachePath = $ConfigCache.FullName
    Remove-Item -Path $ConfigCachePath -Include *.XML -Recurse
    "1" > "$ConfigCachePath\Cache.ini"

    #Restart the Timer Service
    Write-Host "-Starting the Timer Service on $Server" -ForegroundColor Green
    $C = (Get-WmiObject Win32_Service -filter "name='$Timer'" -ComputerName $Server).StartService()
Catch {
      Write-Host "Unable to flush the cache on $Server, please do this manually" -ForegroundColor Red
Write-Host "-Configuration Cache Flush Complete" -ForegroundColor Yellow

Brendan Griffin - @brendankarl