Managing content lifecycle in SharePoint Online is crucial for keeping sites clean, organized, and compliant with data retention policies. Automating content expiration and cleanup using PnP PowerShell helps:
Identify old or unused files
Apply retention policies
Move expired content to archives
Delete obsolete documents
Step 1: Connect to SharePoint Online
Before executing any actions, connect to SharePoint Online:
$siteUrl = "https://yourtenant.sharepoint.com/sites/YourSite"
Connect-PnPOnline -Url $siteUrl -Interactive
✔ Ensures secure authentication.
Step 2: Identify Expired Content
Find documents older than 1 year in a specific library:
$libraryName = "Documents"
$thresholdDate = (Get-Date).AddYears(-1)
$expiredFiles = Get-PnPListItem -List $libraryName | Where-Object {
$_["Modified"] -lt $thresholdDate
}
Write-Host " Found $($expiredFiles.Count) expired files"
✔ Lists old documents for review.
Step 3: Move Expired Files to an Archive
Move old files to an archive library instead of deleting them immediately:
$archiveLibrary = "ArchivedDocuments"
foreach ($file in $expiredFiles) {
$fileUrl = $file["FileRef"]
Move-PnPFile -ServerRelativeUrl $fileUrl -TargetUrl "/sites/YourSite/$archiveLibrary/" -Force
Write-Host " Moved: $fileUrl → $archiveLibrary"
}
✔ Ensures content is retained but organized.
Step 4: Automatically Delete Expired Files
For permanent deletion, remove files older than 2 years:
$deleteThresholdDate = (Get-Date).AddYears(-2)
$filesToDelete = Get-PnPListItem -List $libraryName | Where-Object {
$_["Modified"] -lt $deleteThresholdDate
}
foreach ($file in $filesToDelete) {
Remove-PnPListItem -List $libraryName -Identity $file.Id -Force
Write-Host " Deleted: $($file['FileRef'])"
}
✔ Frees up storage space.
Step 5: Automate Content Cleanup with a Scheduled Task
To run the script weekly, follow these steps:
1️⃣ Save the script as CleanupScript.ps1
2️⃣ Open Task Scheduler → Create Task
3️⃣ Trigger → Weekly
4️⃣ Action → Start program → powershell.exe -File C:\Scripts\CleanupScript.ps1
5️⃣ Ensure script execution policy:
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
✔ Keeps SharePoint clean and optimized.