Partner Technical Services Blog

A worldwide group of consultants who focus on helping Microsoft Partners succeed throughout the business cycle.

SharePoint 2010 Administration with PowerShell: Automating Central Admin Backup

SharePoint 2010 Administration with PowerShell: Automating Central Admin Backup

  • Comments 1
  • Likes

(post courtesy Priyo Lahiri)

Out of the box, SharePoint 2010 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

How can we make this backup script more special?

The script below will send an email if an error occurrs 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.

*Note: The following script is given as a sample, and should be customized and tested in a lab environment long before it is ever run in production. The domain “LZENG” is used in the examples below.

The PowerShell cmdlet that we can use to send the email is a simple one:

Send-MailMessage -From "someaddress@domain.com" -To "YourEmail@domain.com" -Subject "Error captured" -Body “Error Message Here” -SmtpServer YourSMTPServerFQDN

(more parameters are available for the Send-MailMessage cmdlet here: http://technet.microsoft.com/en-us/library/dd347693.aspx)

So I created the simple script below to first see the error message being displayed from PowerShell:

clip_image002

Unfortunately, the error message is not very helpful. It tells me that the backup was not successful but doesn’t give me any pointers as to why. 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 during the back-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… (in pseudocode)

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

   1: $xmldata = [xml](Get-Content 'C:\SPBackup\spbrtoc.xml') #loading spbrtoc.xml as XML datatype
   2:  
   3: # 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
   4:  
   5: $Node = $xmldata.SPBackupRestoreHistory.SPHistoryObject | Where-Object {$_.SPErrorCount -gt '0' -and $_.SPStartTime -gt (Get-Date -DisplayHint Date)}
   6:  
   7: # Getting the SPFailure Message and the spBackup.Log path and creating the body of the email
   8:  
   9: $FailureMsg = $Node[0] | % {$_.SPFailure}
  10: $Att = ($Node[0] | % {$_.SPBackupDirectory}) + 'spbackup.log'
  11: $msgBody = 'An Error occurred while trying to backup your SharePoint Farm. Details : ' + $Failuremsg + '
  12: Attached is the Error Log for additional reference.'
  13:  
  14: # Finally sending the email
  15:  
  16: 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:

image

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: http://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: http://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: http://technet.microsoft.com/en-us/library/dd347693.aspx

Instructions to configure the task:

  1. Put the ps1 file in a folder (for example C:\scripts)
  2. 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”
    clip_image005
  3. Now on the Action tab specify this as the Program / Script
  4. “powershell -command C:\Scripts\BackupFarm.ps1”
    clip_image006
  5. Windows will change it to this:
    clip_image007
  6. 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.

Cheers Smile

-Priyo

More Information

Attachment: BackupFarm.zip
Comments
  • I did try to copy your script, without success, and i did download your script and run it but with no success, it throws me errors like;

    Cannot index into a null array - row 34 and 35

    Does i get it only because the script does not fail and thus the IF($Error[0] -ne $null) throws false and never populates the array?

    thanks

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment