Archive

Archive for the ‘PowerShell’ Category

SharePoint 2010 Farm, Site Collection and My Site Backup PowerShell Script

March 26, 2013 1 comment

Completed my SharePoint 2010 Farm, Site Collection and My Site Backup PowerShell Script.

 

Let me know if you see any bugs:

————————————————————————————–

 

Add-PSSnapin Microsoft.SharePoint.PowerShell

Write-Host "Get-ExecutionPolicy"
Get-ExecutionPolicy
Clear-Host
$Error.Clear()

#PERFORM FULL FARM BACKUP ON ONLY ON SATURDAY
$dayToPerformFullBackup = "Saturday"
$daysToKeepFarmBackup = 7 #NUMBER OF DAYS TO KEEP FARM BACKUP FILES
$dayOfWeek = Get-Date
$externalFarmDiskLocation = [\sharepoint_backup\Farm]
$externalSiteDiskLocation = [\sharepoint_backup\SiteCollection]
$backupFarmFolderForCopy = [UNC path \\servername\backup\Farm]
$backupFarmFolder = [UNC path \\servername\backup\Farm]
$backupSiteFolder = [UNC path \\servername\backup\SiteCollection]

$backupFileSizeTotal = 0
$EventLogName = "SharePoint 2010 Backups"
$EventSource = "SharePoint Powershell"
$ErrorMessage = ""

# Variables below required for Sending Eamil.
$FromAccount = "email account" # valid domain account or an account with Send As rights
[String[]]$ToAccount = "Name1 <email address1>","Name2 <email address 2>" # Recipient email address
$smtpServer = “smtp.emailserver.org” # 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
$emailMessage = ""
$emailMessage += "The $dayOfWeek Sharepoint 2010 Daily Backup Process is completed. The following events were recorded in the $EventLogName event log. `n"
$emailMessage += "———————————————————————– `n"
######################################### START SCRIPT ##############################################
#Create Log
$EventLogMessages = Get-EventLog -LogName $EventLogName 
if($EventLogMessages -eq $null){
New-EventLog -LogName $EventLogName -Source $EventSource
}
######################################################
# FARM BACKUP
try
{
        if($dayOfWeek.DayOfWeek -eq $dayToPerformFullBackup){ # Run complete backup.           
            Write-Host "PERFORMING WEEKLY FARM BACKUP"           
            #Backup-SPFarm -BackupMethod full -Directory $backupFarmFolder -verbose -force -BackupThreads 10
           
        }else{
            Write-Host "SKIPPING WEEKLY FARM BACKUP, NOT SATURDAY, PERFORMING FARM DIFFERENTIAL"
            #Backup-SPFarm -BackupMethod differential -Directory $backupFarmFolder -verbose -force -BackupThreads 10            
        }       
        $spbrtoc = $backupFarmFolder + "\spbrtoc.xml" # Location of TOC
        [xml]$sp = gc $spbrtoc # Import the Sharepoint backup report xml file

        $backupFarmFileXML =  $sp.SPBackupRestoreHistory.SPHistoryObject | Where-Object{$_.SPErrorCount -eq ‘0’ -and $_.SPWarningCount -eq ‘0’ -and ("{0:MM/dd/yy}" -f[datetime]$_.SPFinishTime) -gt((Get-Date -DisplayHint Date).AddDays(-1))}
        $backupFarmFileLocations = $backupFarmFileXML |%{$_.SPBackupDirectory}
        foreach($backupFarmFileLocation in $backupFarmFileLocations){           
                $backupFarmFileSize = (Get-ChildItem $backupFarmFileLocation -Recurse | Measure-Object -Property length -Sum)
                $backupFileSizeTotal += [int]($backupFarmFileSize.Sum/1MB)               
                ######################################################
                #COPY ENVIRONMENT OVER TO EXTERNAL DISK
                #
                Write-Host "COPY FARM BACKUP TO EXTERNAL DISK:$externalFarmDiskLocation"       
                Copy-Item $backupFarmFileLocation -Destination $externalFarmDiskLocation -Recurse -Force   
                if($dayOfWeek.DayOfWeek -eq $dayToPerformFullBackup){
                    Write-EventLog -LogName $EventLogName -EventId 2 -Message "SharePoint Farm FULL Backup completed. File size was $backupFarmFileSize MB"  -Source $EventSource -EntryType Information                       
                }else{
                    Write-EventLog -LogName $EventLogName -EventId 2 -Message "SharePoint Farm DIFFERENTIAL Backup completed. File size was $backupFarmFileSize MB"  -Source $EventSource -EntryType Information   
                }               
                Write-EventLog -LogName $EventLogName -EventId 2 -Message "COPY FARM BACKUP $backupFarmFileLocation TO EXTERNAL DISK:$externalFarmDiskLocation"  -Source $EventSource -EntryType Information   
                ######################################################
        }

        ######################################################
        # FARM BACKUP CLEANUP
        # Find backup sets in TOC
        $archive = $sp.SPBackupRestoreHistory.SPHistoryObject | ? { $_.SPStartTime -lt ((get-date).adddays(-$daysToKeepFarmBackup)) }
        if ($archive -eq $Null) {
            write-host "No backups older than $daysToKeepFarmBackup days found" ;
        }else{
            # Delete the old backups from the Sharepoint backup report xml file
            $archive | % { $sp.SPBackupRestoreHistory.RemoveChild($_) }

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

            # Save the revised backup TOC
            $sp.Save($spbrtoc)
            Write-host "Backup(s) entries older than $daysToKeepFarmBackup days have been removed from spbrtoc.xml and $backupFolder"   
            Write-EventLog -LogName $EventLogName -EventId 2 -Message "Backup(s) entries older than $daysToKeepFarmBackup days have been removed from spbrtoc.xml and $backupFarmFolder"  -Source $EventSource -EntryType Information   
        }
    ######################################################

    ######################################################
    #PERFORM SITE COLLECTION BACKUPS
    #
        Write-Host "PERFORMING TEAM SITE COLLECTION BACKUP"
        #STORE THE BACKUP IN THE DAY OF THE WEEK FOLDER       
        $backupPath = "$backupSiteFolder\$($dayOfWeek.DayOfWeek)"
        write-output "START BACKUPS: Backing Site to $backupPath"       
        $apps = Get-SPWebApplication -IncludeCentralAdministration
        foreach ($app in $apps) {
            $sites = Get-SPSite -WebApplication $app.url -Limit ALL -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
            foreach ($site in $sites) {
                $backupFile = $site.URL.Replace("http://","").Replace("/","_").Replace(":","_");
                $backupCommand = "Backup for Site {0} at {1}\{2}.bak `r`n" -f $site.URL, $backupPath,$backupFile;
                $backupPathAndFile = "{0}\{1}.bak" -f $backupPath,$backupFile;
                Write-Host $backupCommand;
                Write-EventLog -LogName $EventLogName -EventId 1 -Message "$backupCommand started"  -Source $EventSource -EntryType Information           
                try{
                Backup-SPSite -Identity $site.URL -Path $backupPathAndFile -Force   -Verbose   
                $backupFileInfo = Get-ChildItem $backupPathAndFile
                $backupFileSize = [int] ($backupFileInfo.Length/1MB)
                $backupFileSizeTotal += $backupFileSize
                Write-EventLog -LogName $EventLogName -EventId 2 -Message "$backupCommand completed. File size was $backupFileSize KB"  -Source $EventSource -EntryType Information           
                }
                catch{
                    Write-EventLog -LogName $EventLogName -EventId 1 -Message "$backupCommand failed"  -Source $EventSource -EntryType Error           
                }
            }
        }
        ######################################################
        #COPY SITE COLLECTION ENVIRONMENT OVER TO EXTERNAL DISK
        #   
        Write-Host "COPY SITE BACKUP TO EXTERNAL DISK:$externalSiteDiskLocation"       
        Copy-Item $backupPath -Destination $externalSiteDiskLocation -Recurse -Force       
        Write-EventLog -LogName $EventLogName -EventId 2 -Message "COPY SITE COLLECTIONs BACKUP TO EXTERNAL DISK:$externalSiteDiskLocation\$($dayOfWeek.DayOfWeek)"  -Source $EventSource -EntryType Information   
        ######################################################
        # FARM BACKUP CLEANUP
        # Location of TOC
        $spbrtoc = $externalDiskLocation + "\Farm\spbrtoc.xml"
        [xml]$sp = gc $spbrtoc # Import the Sharepoint backup report xml file
        $archive = $sp.SPBackupRestoreHistory.SPHistoryObject | ? { $_.SPStartTime -lt ((get-date).adddays(-$daysToKeepFarmBackup)) } # Find backup sets in TOC
        if ($archive -eq $Null) {
            write-host "No external backups older than $daysToKeepFarmBackup days found" ;
            Write-EventLog -LogName $EventLogName -EventId 1 -Message "No External Backup entries older than $daysToKeepFarmBackup days have been removed from spbrtoc.xml and $externalDiskLocation"  -Source $EventSource -EntryType Information   
        }else{
            # Delete the old backups from the Sharepoint backup report xml file
            $archive | % { $sp.SPBackupRestoreHistory.RemoveChild($_) }

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

            # Save the revised backup TOC
            $sp.Save($spbrtoc)
            Write-host "Backup(s) entries older than $daysToKeepFarmBackup days have been removed from spbrtoc.xml and $backupFolder"   
            Write-EventLog -LogName $EventLogName -EventId 2 -Message "External Backup entries older than $daysToKeepFarmBackup days have been removed from spbrtoc.xml and $externalDiskLocation"  -Source $EventSource -EntryType Information   
        }

}
Catch{
$ErrorMessage = $_.Exception.Message
}
#EMAIL LOGS
$emailSubject = "Daily SharePoint 2010 Backup Report: Backup Job Size: $backupFileSizeTotal MB"
$EventLogMessages = Get-EventLog -LogName $EventLogName  -After ($dayOfWeek) | where {$_.eventID -eq 2}
$emailMessage += "Total amount of data backed up: {0} MB `n" -f $backupFileSizeTotal
if($ErrorMessage -ne "")
{
$emailSubject += " :: WITH ERRORS"
$emailMessage += "———————————————————————– `n"
$emailMessage += "The following were the errors reported today: $ErrorMessage `n"
$emailMessage += "———————————————————————– `n"

}
$emailMessage += "LOG RESULTS: `n"
foreach($message in $EventLogMessages){
    $emailMessage += "{0} `r`n" -f ($message | %{$_.message})   
}
Send-MailMessage -From $FromAccount -To $ToAccount -Subject $emailSubject -Body $emailMessage  -SmtpServer $smtpServer
Write-Host -f Green "Operation Complete"

#Write-Host -ForegroundColor Gray $emailMessage
######################################################

Advertisements