As part of any production SharePoint installation you should always be performing backups. Part of any backup process is deleting the old backup files. In SharePoint as you well know it isn’t as simple as just deleting and folder we also need to update the spbrtoc.xml file so the folder we deleted is no longer listed.

As part of any production SharePoint installation you should always be performing backups. Part of any backup process is deleting the old backup files. In SharePoint as you well know it isn’t as simple as just deleting and folder we also need to update the spbrtoc.xml file so the folder we deleted is no longer listed.

I decided to set our backup job up using PowerShell because of its ability to not only perform simple commands but also edit XML files. Our script is going to do 2 things

  1. Backup our entire SharePoint Farm
  2. Delete backups older than 7 days

Firstly we need to set up our backup location. Ours looks like this:

As you can see we currently have 2 backups (spbr0000, spbr0001), SharePoints backup index file and our PowerShell backup script.

Here is the script


#First we need to load the SharePoint PowerShell Script file
&'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1'
 
#Backup our SharePoint Farm
Backup-SPFarm -Directory \\SharePointBackup -BackupMethod Full -Verbose
 
#Delete Backups older than 7 Days and remove reference from the XML file
$Now = Get-Date
$Days = "7"
$TargetFolder = "\\SharePointBackup"
$LastWrite = $Now.AddDays(-$days)
 
#Get a list of backup folders that begin with "spbr" and were modified more than 7 days ago
$Folders = get-childitem $TargetFolder -include spbr* -exclude *.* -recurse | Where {$_.LastWriteTime -le "$LastWrite"} 
 
$xml = 1(gc $TargetFolder\spbrtoc.xml)
 
foreach ($Folder in $Folders)
{
    if ($Folder)
    {
        write-host "Deleting Folder $Folder" -foregroundcolor "Red"
        Remove-Item $Folder -recurse | out-null
 
        $FolderName = split-path $Folder -Leaf
        $nodes = $xml.SelectNodes("SPBackupRestoreHistory//SPHistoryObject[SPDirectoryName='$FolderName']")
        [void]$xml.SPBackupRestoreHistory.RemoveChild($nodes.item(0));
    }
} 
 
$xml.save("$TargetFolder\spbrtoc.xml")

You may also like

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.