SharePoint Backup Script

Powershell Script

SharePoint offers inbuilt Backup und Restore functionality. It’s always good to have a backup. There are a lot of 3rd Party tools available. But in case you would like to check how to deal with it using Powershell Script and SharePoint native possibilities this post might be interesting for you. Microsoft posted some best practices to this topic of Backup and restore.

SharePoint Backup Considerations

This task of backups should be automated and running fluid. You should not do it manually. You should think about what kind of backups do you plan (full or differential) and how often. In my case we do a full backup each Saturday and all others day we perform a differential backup. A differential backup always need at least one full backup.

The script should run as windows tasks each day. If you create the windows task, keep in mind, to run this task with “highest privileges”.

These backup need storage. Depending on how much data you have in your SharePoint Farm, it can increase rapid. Let’s have a look at the script parts.

Check if you have enough Space before starting backup

Check your storage and exit script if there is not enough space.

#check Storage
$storage = Get-WmiObject Win32_LogicalDisk -ComputerName computerName | where { $_.DeviceID -eq "F:"} 
$freespace = $storage.FreeSpace /1024 /1024 /1024

#exit script if not enough space
if($freespace -lt 300)
{
    #Send Mail Function to inform aboout not enough space
    break
}

This will exit script. You can before send an e-mail to inform you or create a ticket in your ticket system.

Create Backups

#Check Date
$today = Get-Date

if($today.DayOfWeek -eq "Saturday")
    {
    #Creation of the FULL backup
    Write-Host "Backing up the Farm Full... " -f Yellow
    try{
        Backup-SPFarm -Directory "\\Server\SP19_Backup\" -BackupMethod Full -Percentage 5 -Verbose -ErrorAction Stop
        Write-Host "Congratulations! The FULL backup completed successfully!" -f Green
        #Send Mail to inform about success

    }
    catch
    {
        #Send Mail or create ticket about error
    }
}
else{
    #Creation of the Differential backup
    Write-Host "Backing up the Farm Differential... " -f Yellow
    try{
        Backup-SPFarm -Directory "\\\Server\SP19_Backup\" -BackupMethod Differential -Percentage 5 -Verbose -ErrorAction Stop
        Write-Host "Congratulations! The FULL backup completed successfully!" -f Green
        #Send Mail to inform about success
    }
    catch
    {
        #Send Mail or create ticket about error
    }
}

With this script part you create a full backup on Saturday and a differential backup the other days.

Cleanup process – remove backups older than 14 days

#Delete Backups older than 14 Days and remove reference from the XML file
$Now = Get-Date
$Days = "14"
$TargetFolder = "\\Servername\SP19_Backup\"
$xml = [XML] (Get-Content -Path $TargetFolder\spbrtoc.xml)
$LastWrite = $Now.AddDays(-$days)

#Get a list of backup folders that begin with "spbr" and were modified more than 14 days ago

$nodes2Delete = $xml.SPBackupRestoreHistory.ChildNodes | where { $_.SPStartTime -lt $LastWrite}

write-host "Delete every Backup which is older than" $($LastWrite.ToShortDateString()) -ForegroundColor Red
$counterDel = 0;
try{
    
    foreach($node in $nodes2Delete)
    #for($i=$xml.SPBackupRestoreHistory.ChildNodes.Count; $i -ge 0; $i--)
    {
        $nodeDelete = $false;
        #$node = $xml.SPBackupRestoreHistory.ChildNodes[$i]
        #$node = $xml.SPBackupRestoreHistory.ChildNodes[7]
        if($node.SPBackupMethod -eq "Differential")
        {
            write-host "Differential Backup will be deleted $($node.SPStartTime) and $($node.SPBackupDirectory)"
            $nodeDelete = $true
            
        }
        if($node.SPBackupMethod -eq "Full")
        {
        #Only Remove Fullbackup if there is no differential backup between to full backups
            if($node.PreviousSibling.SPBackupMethod -eq "Full")
            {
                write-host "Full Backup will be deleted  $($node.SPStartTime) and $($node.SPBackupDirectory)"
                $nodeDelete = $true
            }
        }
        
        if($nodeDelete -eq $true)
        {
            $FolderName = $node.SPDirectoryName
            $folder = get-item $node.SPBackupDirectory
            write-host "Deleting Folder $Folder" -foregroundcolor "Red"
            Remove-Item $Folder -recurse | out-null

        
            $nodes = $xml.SelectNodes("SPBackupRestoreHistory//SPHistoryObject[SPDirectoryName='$FolderName']")
            [void]$xml.SPBackupRestoreHistory.RemoveChild($nodes.item(0));
            #$node.SPBackupMethod
            $xml.save("$TargetFolder\spbrtoc.xml")
            $counterDel++
            #Send Mail to inform about backup removed with success
        }
    }
    
}
catch
{
    #Send Mail to informabout backup remove script error
}

With this script you can remove older backups from your storage. I got the base idea script from this post and customized it to my needs.

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

About Karsten Schneider 312 Articles
Consultant for Microsoft 365 Applications with a strong focus in Teams, SharePoint Online, OneDrive for Business as well as PowerPlatform with PowerApps, Flow and PowerBI. I provide Workshops for Governance & Security in Office 365 and Development of Solutions in the area of Collaboration and Teamwork based on Microsoft 365 and Azure Cloud Solutions. In his free time he tries to collect tipps and worthy experience in this blog.

Be the first to comment

Leave a Reply