Delete all files in SharePoint site collection (but don't delete document libraries)

Brass Contributor

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?

1 Reply

@Sam1209 

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:

 

https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/introducing-the-pnp-provisioning-...

 

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
        }
    }
}