Wednesday, February 2, 2011

SharePoint 2010 Farm Backup and Cleanup Script

I have spent some time playing with the Powershell Script. I used to have 3 different scripts, but then I decided to combine all of them to one. Which will backup the farm, site collection, then clean and notify administrator about the status.

Here is the script that I want to share.
1) Backup the Site Collection
2) Backup the SharePoint Farm
3) Clean up the old Farm backup and Site Collection backup files
4) Log deleted file into cleanup.log
5) Notify Administrator about the Status.

* Updated on 04 Jan 2012 - improve error handling *
##==================================================================##
## PowerShell SharePoint 2010 Farm Backup, Cleanup and Email Script ##
## Version: 2.0 ##
## Last updated: 04 Jan, 2012 ##
## Description: This script will perform the following ##
## 1) Backup Site Collection ##
## 2) Backup SharePoint Farm ##
## 3) Cleanup old backup and old farm backup ##
## 4) Log deleted file in cleanup.log ##
## 5) Send out status email ##
##==================================================================##

$snapin = Get-PSSnapIn -name "Microsoft.SharePoint.PowerShell" -registered
if(!$snapin)
{
Add-PSSnapIn Microsoft.SharePoint.PowerShell
}

$today = (Get-Date -Format yyyy-MM-dd)
$collectionBackupPath ="\\SP2010\E$\Scheduled_Backups\Site-80\"
$farmBackupPath = "\\SP2010\E$\Scheduled_Backups\Farm\"
$webSite = "http://SP2010"

##Cleanup Backup that is older then x day.
$days = 7

##Variables for Email
$emailFrom = "SP2010@SharePoint4Newbie.com"
$emailTo = "administrator@SharePoint4Newbie.com"
$smtpServer = "MailServer.SharePoint4Newbie.com"


## Send Mail Function
Function sendEmail
{
param($from,$to,$subject,$smtphost,$body)
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body
#$msg.isBodyhtml = $true
$smtp.send($msg)
}

Try
{
$backupFile = $collectionBackupPath + $today + ".Bak"

## Backing up SharePoint Collection
Backup-SPSite -Identity $webSite -Path $backupFile -Force -ea Stop

## Backing up SharePoint Farm
Backup-SPFarm -directory $farmBackupPath -backupmethod Full

## Location of spbrtoc.xml
$spbrtoc = $farmBackupPath + "spbrtoc.xml"

## Import the Sharepoint backup report xml file
[xml]$sp = gc $spbrtoc

## Find the old backups in spbrtoc.xml
$old = $sp.SPBackupRestoreHistory.SPHistoryObject | Where { (Get-Date $_.SPStartTime) -lt ((get-date).adddays(-$days)) }
if ($old -eq $Null) { write-host "No reports of backups older than " + $days + " days found in spbrtoc.xml.`nspbrtoc.xml isn't changed and no files are removed.`n" ; break}

if ($old -eq $Null)
{
Add-Content $farmBackupPath"cleanup.log" "$date - Farm BK Script - No reports of backups older than $days days found in spbrtoc.xml. spbrtoc.xml isn't changed and no files are removed.`n";
}
else
{
## Delete the old backups from the Sharepoint backup report xml file
$old | % { $sp.SPBackupRestoreHistory.RemoveChild($_) }

## Delete the physical folders in which the old backups were located
$old | % { Remove-Item $_.SPBackupDirectory -Recurse }

## Save the new Sharepoint backup report xml file
$sp.Save($spbrtoc)

##Write-host "Backup(s) entries older than " + $portalRecycleDays + " days are removed from spbrtoc.xml and harddisc."
Add-Content $farmBackupPath"cleanup.log" "$date - Farm BK Script - Backup(s) entries older than $portalRecycleDays days are removed from spbrtoc.xml and harddisc.";
}

## Remove Previous Site Collection Backup
$LastWrite = [DateTime]::Now.AddDays(-$days)
$Files = get-childitem $collectionBackupPath"*.bak" | Where {$_.LastWriteTime -le "$LastWrite"}
if (!$Files)
{
Add-Content $collectionBackupPath"cleanup.log" "$date - Farm BK Script - No backup file is older than $LastWrite ";
}
else
{
foreach ($File in $Files)
{
##Deleting old backup file
Remove-Item $File -Force
Add-Content $collectionBackupPath"cleanup.log" "$date - Farm BK Script - Deleted file $File ...";
}
}

## Composed a status update email for administration
$emailSubject = "SharePoint Farm Backup is completed"
$emailBody = "SharePoint Farm Backup is completed successfully on "+ $today + "`r`n`r`nFarm backup can be found at $webSite:9999/_admin/BackupHistory.aspx`r`n`r`nBackup files are located at $collectionBackupPath";
sendEmail $emailFrom $emailTo $emailSubject $smtpServer $emailBody
}
Catch
{
## Composed a status update email for administration
$ErrorMessage = $_.Exception.Message
$emailSubject = "SharePoint Farm Backup Job failed on "+$today
$emailBody = "SharePoint Farm Backup Job failed on "+ $today + "`r`n`r`nThe reason of the failure was: $ErrorMessage."
sendEmail $emailFrom $emailTo $emailSubject $smtpServer $emailBody
}
Finally
{
## Unlock the site
Set-SPSite -Identity $webSite -LockState "Unlock"
}

##==================================================================##


You can copy the script and save to the harddrive (example c:\Powershell\SPBackupCleanup.ps1), then create a Windows Tasks Scheduler to execute the script everyday... With that, you should sleep better at night :)
Please TEST the script multiple times before using in production...
Tips:
use Windows Powershell to restore a farm
1) On the Start menu, click All Programs.
2) Click Microsoft SharePoint 2010 Products.
3) Click SharePoint 2010 Management Shell.

4) Enter the following Script to get the Backup GUID
Get-SPBackupHistory -Directory \\SP2010\E$\Scheduled_Backups\Farm -ShowBackup

5) Enter the following to Restore the farm
Restore-SPFarm -Directory \\SP2010\E$\Scheduled_Backups\Farm -RestoreMethod Overwrite -BackupId [backup GUID]

Good Luck!
Reference of my script were from "Automate SharePoint 2010 Farm Backups with Powershell" by Alex

6 comments:

  1. It looks like some of your pipes (|) disappeared?

    Two before the Where clauses and two after the $old variable?

    - Dave

    ReplyDelete
  2. Good catch David and thanks! It has just been corrected...
    Apparently I can only enter the pipe in Edit HTML mode... The regular edit mode will "eat" the pipe :)

    ReplyDelete
  3. Hi,
    In your script u have just taking farm full backup. where i need to take farm full back bi-monthly and take farm Diff backup daily.would u pls update script or guide me how i can add this thing in script.
    thanks

    ReplyDelete
  4. Hi Irfan,
    The shell script will backup the SP farm and send email, for bi-monthly backup, you need to create a new task in Windows Task Scheduler, then set the execution date time, see link below. Hope this help. http://www.hosting.com/support/windows-server-2008/create-a-scheduled-task-in-windows-server-2008
    Thanks!

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Keat-Hau,
    Can you please provide me the script to take a differential backup of the SHP farm?
    Also, I need the store all the site collection backups in a separate folder, can you please provide me the script for that? Thanks in advance.

    ReplyDelete