Automating SharePoint 2010 Administration with PowerShell: Automating Central Admin Backup
SharePoint 2010 out-of-the-box doesn’t have the capability of scheduling a backup. Fortunately, we have the mix of PowerShell script and Windows Task Scheduler to do the job. In reality it’s just a single line script:
Backup-SPFarm –Directory YourBackupDirectory –BackupMethod Full / Differential
So what’s so special about this specific script?
It sends you an email if an error occurred during the backup with the error description so that every morning (or whatever your backup schedule is) you don’t have to open up Central Admin and see if the backup went fine or not (assuming you check the backup status / integrity…. I know a lot of people who don’t!) and hopefully it gives you an idea on what went wrong.
The cmd-let that we can use to send the email is a simple on:
Send-MailMessage -From "someaddress@domain.com" -To "YourEmail@domain.com" -Subject "Error captured" -Body “Error Message Here” -SmtpServer YourSMTPServerFQDN
So I created the simple script below to first see the error message being displayed from PowerShell:
Unfortunately, the error message is not very helpful. It tells me that the backup was not successful but doesn’t give me any pointer. No point sending this to the SharePoint admin. Let’s take a look at the spbrtoc.xml from the backup directory:
<SPHistoryObject>
<SPId>376aa7dd-0e79-4e8e-9247-26d5a61949b7</SPId>
<SPRequestedBy>LZENG\administrator</SPRequestedBy>
<SPBackupMethod>Full</SPBackupMethod>
<SPRestoreMethod>None</SPRestoreMethod>
<SPStartTime>02/24/2011 18:15:15</SPStartTime>
<SPFinishTime>02/24/2011 18:15:41</SPFinishTime>
<SPIsBackup>True</SPIsBackup>
<SPConfigurationOnly>False</SPConfigurationOnly>
<SPBackupDirectory>\\app02\SPBackup\spbr000D\</SPBackupDirectory>
<SPDirectoryName>spbr000D</SPDirectoryName>
<SPDirectoryNumber>13</SPDirectoryNumber>
<SPFailure>Object lz_Admin failed in event OnBackup. For more information, see the spbackup.log or sprestore.log file located in the backup directory.</SPFailure>
<SPTopComponent>Farm</SPTopComponent>
<SPTopComponentId>d1047b6f-4ff1-4ce4-943b-f54ff5fe44e3</SPTopComponentId>
<SPWarningCount>0</SPWarningCount>
<SPErrorCount>1</SPErrorCount>
</SPHistoryObject>
Now that makes a little more sense, I can now see that the Admin Content Database failed when trying to be backup up. So how about sending this to the SharePoint Admin so that he knows exactly what’s going on? To make this more useful, we will also attach the backup log from the SPBackupDirectory with the email so that the SharePoint admin knows everything he needs to about the error.
Here is how we do it…
Read the spbrtoc.xml file and pull up the First <SPHistoryObject> block and get the path of the spbackup.txt from <SPBackupDirectory> and attach it to the email. Here is a script sample
$xmldata = [xml](Get-Content 'C:\SPBackup\spbrtoc.xml') #loading spbrtoc.xml as XML datatype
# In the statement below I am getting the block of <SPHistoryObject> where SPErrorCount is more than zero and the #SPHistoryObject was created today and storing it in $Node
$Node = $xmldata.SPBackupRestoreHistory.SPHistoryObject | Where-Object {$_.SPErrorCount -gt '0' -and $_.SPStartTime -gt (Get-Date -DisplayHint Date)}
# Getting the SPFailure Message and the spBackup.Log path and creating the body of the email
$FailureMsg = $Node[0] | % {$_.SPFailure}
$Att = ($Node[0] | % {$_.SPBackupDirectory}) + 'spbackup.log'
$msgBody = 'An Error occurred while trying to backup your SharePoint Farm. Details : ' + $Failuremsg + '
Attached is the Error Log for additional reference.'
# Finally sending the email
Send-MailMessage -From 'administrator@lzeng.local' -To 'Administrator@lzeng.local' -Subject 'Error Occured in SharePoint Backup' -Body $msgBody -Attachments $att -SmtpServer mail.lzeng.local
And here is the result:
Here is the full script:
1: Clear-Host
2: $Error.Clear()
3: ###################################################################################################
4: #################### POPULATE THE VARIABLES BELOW ##################################################
5: ###################################################################################################
6:
7: $BackupDir = '\\app02\SPBackup' # Your backup directory here. Recommended to use \\server\share
8: # NOTE: DO NOT put '\' after the above path
9: # Ensure SharePoint Timer Service Account and SQL Service Account has Full Control on the above Path
10: # More Information: https://technet.microsoft.com/en-us/library/ee748614.aspx
11:
12: # Variables below required for Sending Email.
13: $FromAccount = 'administrator@lzeng.local' # valid domain account or an account with Send As rights
14: $ToAccount = 'administrator@lzeng.local' # Recipient email address
15: $smtpServer = 'mail.lzeng.local' # SMTP / Exchange / SMTP Relay Agent FQDN
16: # If you need other parameters like CC Field or if you exchange uses SSL refer here: https://technet.microsoft.com/en-us/library/dd347693.aspx
17: ######################################### START SCRIPT ##############################################
18:
19: # Start Loading SharePoint Snap-in
20: $snapin = (Get-PSSnapin -name Microsoft.SharePoint.PowerShell -EA SilentlyContinue)
21: IF ($snapin -ne $null){write-host -f Green "SharePoint Snap-in is loaded... No Action taken"}
22: ELSE { write-host -f Yellow "SharePoint Snap-in not found... Loading now"
23: Add-PSSnapin Microsoft.SharePoint.PowerShell
24: write-host -f Green "SharePoint Snap-in is now loaded"}
25: # END Loading SharePoint Snapin
26:
27: # Starting Backup
28: Write-Host -f green "Staring Backup process"
29: Backup-SPFarm -Directory $BackupDir -BackupMethod full -BackupThreads 10 -Force -ErrorAction SilentlyContinue
30: Write-Host -f green "Exit: Backup process"
31:
32: IF($Error[0] -ne $null){
33: # Loading toc file
34: $xmldata = [xml](Get-Content ($BackupDir +'\spbrtoc.xml'))
35: $Node = $xmldata.SPBackupRestoreHistory.SPHistoryObject | Where-Object {$_.SPErrorCount -gt '0' -and $_.SPStartTime -gt (Get-Date -DisplayHint Date)}
36: # Grab SPFailure Msg and Path to attachment
37: $FailureMsg = $Node[0] | % {$_.SPFailure}
38: $Att = ($Node[0] | % {$_.SPBackupDirectory}) + 'spbackup.log'
39: # Create msgbody
40: $msgBody = 'An Error occurred while trying to backup your SharePoint Farm. Details : ' + $Failuremsg + '
41: Attached is the Error Log for additional reference.'
42:
43: # Send email
44: Send-MailMessage -From $FromAccount -To $ToAccount -Subject 'Error Occured in SharePoint Backup' -Body $msgBody -Attachments $att -SmtpServer $smtpServer }
45:
46: Write-Host -f Green "Operation Complete"
47: ############################################## END SCRIPT ##############################################
A workable script is attached with this post that you can download and use. All you need to do it specify values for the variables below and follow the instructions to create a task in Windows Task Scheduler.
Variables to populate in the script:
$BackupDir = '\\app02\SPBackup' # Your backup directory here. Recommended to use \\server\share
NOTE: DO NOT put '\' after the above path
$FromAccount = 'administrator@lzeng.local' # valid domain account or an account with Send As rights
$ToAccount = 'administrator@lzeng.local' # Recipient email address
$smtpServer = 'mail.lzeng.local' # SMTP / Exchange / SMTP Relay Agent FQDN
If you need other parameters like CC Field or if you exchange uses SSL refer here: https://technet.microsoft.com/en-us/library/dd347693.aspx
Instructions to configure the task:
Put the ps1 file in a folder say C:\scripts
Now in your task scheduler, configure the task to run in highest privilege and choose the option to “Run whether user is logged on or not”
Now on the Action tab specify this as the Program / Script
“powershell -command C:\Scripts\BackupFarm.ps1”
Windows will change it to this:
In the Trigger create a schedule to run the task every night at 2 AM (or whatever suits your schedule).
You are all set.
If you want you can create 2 copies of this script and change the second one to run Differential backup every night and Full Backup every Sunday or whatever your backup strategy is.
Ok so now you know I can read the xml file from PowerShell which means I can also remove some lines from it and may be have a cleanup script for backup retention and remove all those failed backup listed in the central admin? You are right on… but that’s for the next post.
Stay tuned.
CheersJ
Priyo