Unused SharePoint Online modern and classic pages can clutter sites, consume storage, and reduce search efficiency. Automating their removal helps:
Improve content hygiene
Optimize search performance
Reduce storage costs
With PnP PowerShell, we can:
✔ Identify old or unused pages
✔ Archive or delete them
✔ Schedule automatic cleanup
Step 1: Connect to SharePoint Online
$siteUrl = "https://yourtenant.sharepoint.com/sites/YourSite"
Connect-PnPOnline -Url $siteUrl -Interactive
Write-Host " Connected to SharePoint Online"
✔ Ensures secure authentication.
Step 2: Identify Unused Pages
Find pages not modified in the last 6 months:
$libraryName = "Site Pages"
$thresholdDate = (Get-Date).AddMonths(-6)
$unusedPages = Get-PnPListItem -List $libraryName | Where-Object {
$_["Modified"] -lt $thresholdDate
}
$unusedPages | Format-Table -Property Title, FileRef, Modified -AutoSize
Write-Host " Identified unused pages"
✔ Filters out inactive content.
Step 3: Archive Pages Before Deletion
Move unused pages to an archive folder instead of deleting immediately:
$archiveLibrary = "Archived Pages"
if (!(Get-PnPList | Where-Object { $_.Title -eq $archiveLibrary })) {
New-PnPList -Title $archiveLibrary -Template DocumentLibrary
Write-Host " Created archive library: $archiveLibrary"
}
foreach ($page in $unusedPages) {
Move-PnPFile -ServerRelativeUrl $page["FileRef"] -TargetUrl "/sites/YourSite/$archiveLibrary"
Write-Host " Moved page to archive: $($page['Title'])"
}
✔ Prevents accidental data loss.
Step 4: Delete Unused Pages
Remove archived pages older than 1 year:
$thresholdDate = (Get-Date).AddYears(-1)
$pagesToDelete = Get-PnPListItem -List $archiveLibrary | Where-Object {
$_["Modified"] -lt $thresholdDate
}
foreach ($page in $pagesToDelete) {
Remove-PnPListItem -List $archiveLibrary -Identity $page.Id -Force
Write-Host " Deleted page: $($page['Title'])"
}
✔ Ensures safe content removal.
Step 5: Automate the Script (Task Scheduler)
Schedule cleanup monthly:
$taskAction = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\DeleteUnusedPages.ps1"
$taskTrigger = New-ScheduledTaskTrigger -Monthly -DaysOfMonth 1 -At 2AM
Register-ScheduledTask -TaskName "Delete Unused SharePoint Pages" -Action $taskAction -Trigger $taskTrigger -RunLevel Highest
✔ Automates ongoing maintenance.