Skip to content

SharePoint Farm Backup Powershell Script With Error Catching, Logging, and Email Notifications

by on April 14, 2015

The below works pretty well for me – note that you may want to check for converted quote marks and put in your own paths/etc.

There are a few additional details commented out to assist in tweaking to your own needs.

This can be run as a scheduled tasks as a powershell parameter, providing permissions are set appropriately.

 

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

#set email address to mail report/logs to
$email = "ebruce@mydomain.com"
$erroremail = "alerts@mydomain.com"
#############set parameters
$a = Get-Date -format yyyy-MM-dd-HH-mm
$aa = Get-Date -format "yyyy-MM-dd HH:mm"
$aaa = Get-Date -format yyyy-MM-dd
$reportname = "SPTestFarm_Backups"
$errorlog = "c:\ps_output\$reportname_$aaa.log"
$filepath = "\\backuphost\SharePoint2013\SPTestFarm\" #include trailing slash
$DeleteIfOlderThan = (get-date).addminutes(-1)
#$DeleteIfOlderThan = (get-date).adddays(-8)

Write-host SPFarm Backup starting
"————————————————-"| add-content $errorlog
"[$aa] SPFarm Backup Starting"| add-content $errorlog

try{
    #### uncomment next line to test for error catching
    #$test = ebruce@mydomain.com
    Write-host "Full Backup Job In Progress – test"

    #############  remove directory
    #get item properties list
    #Get-ItemProperty -Path \\backuphost\SPFarm2013_Backup\farm\farm | Format-list -Property * -Force
    #Get-ItemProperty -Path \\backuphost\SPFarm2013_Backup\farm\farm | Get-Member -MemberType property
    #write-host Get subfolders
    #Get-ChildItem -Path $filepath
    write-host Remove Folders Older Than $Deleteifolderthan…
    $aa = Get-Date -format "yyyy-MM-dd HH:mm"
    "[$aa] Removing Folders Older Than $Deleteifolderthan" | add-content $errorlog
    Get-ChildItem -Path $filepath | ForEach-Object{
        if($_.CreationTime -le $deleteifolderthan){
            $string = $filepath+$_.name;
            write-host $_.name,$_.creationtime;
            $aa = Get-Date -format "yyyy-MM-dd HH:mm"
            "[$aa] Removing $string – recursive" | add-content $errorlog
            remove-item -path $string -recurse -force}
        }

    #Make bak directory
    write-host make new directory name…
    $newdirectory = $filepath+’farm_’+$a
    write-host Creating new directory $newdirectory
    $aa = Get-Date -format "yyyy-MM-dd HH:mm"
    "[$aa] Creating new directory $newdirectory" | add-content $errorlog
    new-item -path $newdirectory -itemtype directory

    #backup SP full
    Write-host Running SharePoint: Full Backup to $newdirectory
    $aa = Get-Date -format "yyyy-MM-dd HH:mm"
    "[$aa] Error Detail: Running SharePoint: Full Backup to $newdirectory" | add-content $errorlog
    Backup-SPFarm -BackupMethod Full -Directory $newdirectory

#sp 2007 with spsadm – use –showtree like –whatif for testing

#stsadm -o backup -directory $farmpath -backupmethod Full -percentage 1 -backupthreads 3

    #Differential Backup
    #write-host Differential Backup Job In Progress
    #$path = "\\backuphost\SharePoint2013\farm\"
    #$folder = gci $path | where-object { $_.PSIsContainer} | sort CreationTime -desc | select -f 1
    #$folderpath = $path+$folder
    #write-host Writing Incremental to $folderpath
    #Backup-SPFarm -BackupMethod Differential -Directory $folderpath -WhatIf

}
catch [system.exception]{ #Use most specific catch first – catches any/all errors – base class generic
    #email with
    $aa = Get-Date -format "yyyy-MM-dd HH:mm"
    "[$aa] Error: See Central Administration Backup and Restore Job Status & History details located http://sptest:2013/_admin/BackupStatus.aspx and http://sptest:2013/_admin/BackupHistory.aspx" | add-content $errorlog
    "Error: $_" | Write-host -foregroundcolor red
    $aa = Get-Date -format "yyyy-MM-dd HH:mm"
    "[$aa] Error Detail: $_" | add-content $errorlog
$emailstring = "Backup Completed"
}
finally{
    Write-host SPFarm Backup Ending
    $aa = Get-Date -format "yyyy-MM-dd HH:mm"
    "[$aa] SPFarm Backup Complete"| add-content $errorlog

$emailstring = "Backup Error"

#mail report
#############Email
write-host "Mailing $errorlog to $email"
$smtp = New-Object Net.Mail.SmtpClient("mail.mydomain.com")
    $objMailMessage = New-Object System.Net.Mail.MailMessage
    $objMailMessage.From = "sptest@mydomain.com"
    $objMailMessage.To.Add($email)
    $objMailMessage.Subject = $reportname + "_Report"
    $objMailMessage.Body = $Reportname + "_Report: " + $emailstring

   ##Create  the file attachment for this e-mail message.
   #$data = New-Object Net.Mail.Attachment($filepath)
   $data = New-Object Net.Mail.Attachment($errorlog)
   $objMailMessage.Attachments.Add($data)

$smtp.send($objMailMessage) | Out-Null

write-host "waiting for smtp…"
$data.Dispose();
$objMailMessage.Dispose();

###########Delete created csv file
#write-host "deleting $errorlog"
#TODO: decide if logs should be removed
#Remove-Item "$filepath"
#While(Test-Path $filepath) {Remove-Item $filepath}

Advertisements
Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: