Document archival is essential for managing large volumes of SharePoint Online content. Automating this process using PnP PowerShell helps in:
✔ Moving old files to an archive library or site
✔ Reducing active library clutter
✔ Enforcing retention policies
✔ Enhancing SharePoint performance
Step 1: Install and Connect to SharePoint Online
Ensure PnP PowerShell is installed:
Install-Module -Name PnP.PowerShell -Force -AllowClobber
Update the module if needed:
Update-Module -Name PnP.PowerShell
Now, connect to SharePoint Online:
Connect-PnPOnline -Url "https://yourtenant.sharepoint.com/sites/YourSite" -Interactive
✔ Uses interactive login for authentication.
Step 2: Identify Old Documents for Archival
Find documents older than 1 year (365 days):
$library = "Documents"
$thresholdDate = (Get-Date).AddDays(-365)
$oldFiles = Get-PnPListItem -List $library | Where-Object {
$_.FieldValues["Created"] -lt $thresholdDate
}
Write-Host "Found $($oldFiles.Count) files for archival."
✔ Retrieves documents older than 365 days.
Step 3: Move Old Documents to an Archive Library
Create an Archive Library if not already present:
New-PnPList -Title "ArchivedDocuments" -Template DocumentLibrary
Now, move files:
foreach ($file in $oldFiles) {
$fileUrl = $file.FieldValues["FileRef"]
$fileName = $file.FieldValues["FileLeafRef"]
Move-PnPFile -ServerRelativeUrl $fileUrl -TargetUrl "/sites/YourSite/ArchivedDocuments/$fileName" -Force
Write-Host "Moved: $fileName to Archive"
}
✔ Moves old documents from ‘Documents’ to ‘ArchivedDocuments’.
Step 4: Automate Archival with Task Scheduler
- Save the script as
ArchiveDocuments.ps1
. - Open Task Scheduler → Create Basic Task.
- Set Trigger → Monthly.
- Set Action → Start a Program.
- Use this PowerShell command:
-ExecutionPolicy Bypass -File "C:\Scripts\ArchiveDocuments.ps1"
✔ Ensures automatic document archival every month.
Step 5: Verify Archived Documents
Run the following to check archived files:
Get-PnPListItem -List "ArchivedDocuments" | Select-Object FieldValues
✔ Confirms documents were successfully archived.