Backing up SharePoint Online is critical to prevent data loss due to accidental deletions, cyberattacks, or misconfigurations. While Microsoft 365 provides retention policies and versioning, having an external backup strategy using PnP PowerShell ensures additional security.
This guide will help you create a comprehensive SharePoint Online backup strategy using PnP PowerShell, covering:
✔ Backing up site collections
✔ Exporting document libraries
✔ Saving lists and metadata
✔ Automating backups
Step 1: Install and Connect to SharePoint Online
Ensure you have PnP PowerShell installed:
Install-Module -Name PnP.PowerShell -Force -AllowClobber
Update-Module -Name PnP.PowerShell
Connect to SharePoint Online:
Connect-PnPOnline -Url "https://yourtenant.sharepoint.com/sites/YourSite" -Interactive
Step 2: Backup SharePoint Site Collections
You can export site collection structure using:
$backupPath = "C:\Backups\SiteBackup.xml"
Get-PnPSiteTemplate -Out $backupPath
Write-Host "Site collection structure exported to $backupPath"
✔ Saves site structure, lists, libraries, and settings.
To restore the site structure:
Invoke-PnPSiteTemplate -Path $backupPath
Write-Host "Site structure restored from backup."
Step 3: Backup Document Libraries
To download all files from a library:
$libraryName = "Documents"
$backupFolder = "C:\Backups\Documents"
# Create backup folder if not exists
If (!(Test-Path -Path $backupFolder)) { New-Item -ItemType Directory -Path $backupFolder }
# Retrieve files and download
$files = Get-PnPListItem -List $libraryName
foreach ($file in $files) {
$fileUrl = $file["FileRef"]
$localFilePath = "$backupFolder\$($file["FileLeafRef"])"
Get-PnPFile -Url $fileUrl -Path $backupFolder -FileName $file["FileLeafRef"] -AsFile
Write-Host "Downloaded: $fileUrl"
}
Write-Host "Document library backup completed."
✔ Saves all files locally for external storage.
Step 4: Backup Lists and Metadata
To export list items:
$backupFile = "C:\Backups\ListBackup.csv"
$listName = "Tasks"
Get-PnPListItem -List $listName | Export-Csv -Path $backupFile -NoTypeInformation
Write-Host "List items exported to $backupFile"
To restore the list data:
$importData = Import-Csv -Path $backupFile
foreach ($item in $importData) {
Add-PnPListItem -List $listName -Values @{
"Title" = $item.Title;
"Description" = $item.Description
}
}
Write-Host "List data restored."
✔ Retains metadata and list structure.
Step 5: Automate Backups with Task Scheduler
To schedule daily backups:
- Save the script as
SharePointBackup.ps1
. - Open Task Scheduler → Create Basic Task.
- Set Trigger → Daily at 2:00 AM.
- Set Action → Start a Program.
- Use this PowerShell execution command:
-ExecutionPolicy Bypass -File "C:\Scripts\SharePointBackup.ps1"
✔ Ensures automatic backups without manual intervention.
Step 6: Verify Backup Integrity
To check if all backups are successful:
Get-ChildItem -Path "C:\Backups" | Select Name, Length, LastWriteTime
✔ Confirms files were saved correctly.