Script: Clearing the SharePoint configuration cache on all servers in the farm

Need to clear the configuration cache on all of your SharePoint servers but don’t want to take the time to do it manually?

If you’ve configured PowerShell Remoting between the farm servers and are logged onto any server in the farm with an administrative account, you can run this script to automate this process.

Note the folder is for SharePoint 2010 and SharePoint 2013.

I borrowed the bulk of the clearing code from Thomas Bernhard’s blog post Clear SharePoint Config Cache with PowerShell and wrapped it in a script block so we can run it remotely.

Save the code below in a .ps1 and run it from one of the SharePoint servers in the farm in an elevated PowerShell window (you could also just paste it into the PowerShell window if you’re into that sort of thing).

#Script block for stopping the timer service
$sb_stop = {
	Write-Output "`t$($env:computername)"
	Stop-Service -Name "SPTimerV4"
}

#Script block for starting the timer service
$sb_start = {
	Write-Output "`t$($env:computername)"
	Start-Service -Name "SPTimerV4"
}

#Script block for finding and clearing the configuration cache
$sb_cache = {
	Write-Output "`t$($env:computername)"
	
	$folders = Get-ChildItem "C:\ProgramData\Microsoft\SharePoint\Config"
	
	foreach ($folder in $folders) {
		$items = Get-ChildItem $folder.Fullname -Recurse
		foreach ($item in $items) {
			if ($item.Name.ToLower() -eq "cache.ini") {
				$cachefolder = $folder.FullName
			} #if
		} #foreach item
	} #foreach folder
	
	Write-Output "`tDeleting xml..."	
	$cachefolderitems = Get-ChildItem $cachefolder -Recurse
	foreach ($cachefolderitem in $cachefolderitems) {
		if ($cachefolderitem -like "*.xml") {
			$cachefolderitem.Delete()
		} #if
	} #foreach
	
	Write-Output "`tResetting cache ini..."
	$a = Get-Content $cachefolder\cache.ini
	$a = 1
	Set-Content $a -Path $cachefolder\cache.ini

} # sb


Add-PSSnapin Microsoft.SharePoint.PowerShell
$servers = Get-SPServer | where {$_.Role -eq "Application"} | select -ExpandProperty Address
Write-Output "Servers in the farm: $servers"


#Stop timer
foreach ($server in $servers) {
	Write-Output "Stopping Timer Service on $server"
	Invoke-Command -Computername $server -ScriptBlock $sb_stop
	Write-Output " "
}

#Clear cache
foreach ($server in $servers) {
	Write-Output "Clearing configuration cache on $server"
	Invoke-Command -Computername $server -ScriptBlock $sb_cache
	Write-Output " "
}

#Start Timer
foreach ($server in $servers) {
	Write-Output "Starting Timer Service on $server"
	Invoke-Command -Computername $server -ScriptBlock $sb_start
	Write-Output " "
}

The output will look something like this:
clearconfigcache

Share Button