Nov 10 2023 08:46 AM
I am trying to find a PowerShell script that deletes all files across hundreds of document libraries in a single SharePoint site collection.
The document libraries must not be deleted.
Is anyone able to help?
Nov 10 2023 05:17 PM - edited Nov 10 2023 05:18 PM
I would recommend creating a new site collection instead and recreating the document libraries and Archive the site, just in case any file are needed... Easiest way you can do this if you have that many document libraries is to use PnP Provisioning! Just get the template from the old site and apply it to the new site, I Highly recommend this method over deleting all files:
But if you still feel you need script, here you go:
Here are two scripts, one for a single site collection and one for the whole tenant!
Use this at your own risk
Specific site:
# Import the PnP PowerShell module
Import-Module PnP.PowerShell
# Connect to your SharePoint Online tenant
Connect-PnPOnline -Url ""
# Get all document libraries in the site
$documentLibraries = Get-PnPList | Where-Object {$_.BaseTemplate -eq 101 -and $_.Hidden -eq $false} #Or $_.BaseType -eq "DocumentLibrary"
# Iterate through each document library and delete all files
foreach ($documentLibrary in $documentLibraries) {
# Get all files in the document library
$files = Get-PnPListItem -ListUrl $documentLibrary.Url
# Delete all files in the document library
foreach ($file in $files) {
Remove-PnPFile -Url $file.Url
}
}
Whole tenant(BE CAREFUL!) :
# Import the PnP PowerShell module
Import-Module PnP.PowerShell
# Connect to your SharePoint Online tenant
Connect-PnPOnline -Url ""
# Get all SharePoint site URLs
$siteUrls = Get-PnPTenantSite
# Iterate through each SharePoint site and get all files
foreach ($siteUrl in $siteUrls) {
# Get all document libraries in the site
$documentLibraries = Get-PnPList | Where-Object {$_.BaseTemplate -eq 101 -and $_.Hidden -eq $false} #Or $_.BaseType -eq "DocumentLibrary"
# Iterate through each document library and delete all files
foreach ($documentLibrary in $documentLibraries) {
# Get all files in the document library
$files = Get-PnPListItem -ListUrl $documentLibrary.Url
# Delete all files in the document library
foreach ($file in $files) {
Remove-PnPFile -Url $file.Url
}
}
}