Delete specific files in SharePoint

Delete specific files in SharePoint

Have you ever been in a situation where you need to delete files of a certain type, or file names containing some key words? Well, I have recently.

After a – in general – successfull migration from on-prem file server to SharePoint we noticed that we also copied over a bunch of temporary files (*.tmp) and files beginning with the characters ~$. This is temporary files and garbage from Word and Excel that’s been accumulated over the years and not something we need to store. How on earth are we going to clean up this mess?

As always, PowerShell to the rescue! Make sure you are up to date on your PS Module called PnP.PowerShell by running this:

Update-Module -Name PnP.PowerShell

If you don’t have it already, run this:

Install-Module -Name PnP.PowerShell

Warning:

In version 1.11.0 of PnP PowerShell there is a bug that breaks this method. Try install the very latest release with this command:
Install-Module -Name PnP.PowerShell -AllowClobber -AllowPrerelease -SkipPublisherCheck

Next we need to give this module permission to do stuff in our tenant. To trigger a consent prompt, we use this:

Register-PnPManagementShellAccess

Log in with a user with appropriate rights to be able to consent applications in Azure AD.

The script

Below is the complete script you can run to get rid of all files of a spesific type in a SharePoint document library. Take note of the variables you need to adjust to fit your need.

$SiteURL = "https://customer.sharepoint.com/sites/AllTheFiles"
$LibraryName = "Shared Documents"
$SearchString = "*.tmp"

#Connect to SharePoint Online
Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)

#Create a list of files that matches the search string
$Files = Find-PnPFile -List $LibraryName -Match $SearchString

ForEach ($File in $Files)
{
    Write-Host ("Deleting file: '{0}' at '{1}'" -f $File.Name, $File.ServerRelativeURL)
    
    #Deletes the item
    Remove-PnPFile -ServerRelativeUrl $File.ServerRelativeURL -Force -Recycle
        
}

#Optional: Empty the recycle bin. Comment out or not use this if you want to let the files remain in recycle bin.

Get-PnPRecycleBinItem | Where-Object LeafName -like $SearchString | Clear-PnpRecycleBinItem -Force

Sources:

PnP PowerShell | PnP PowerShell

One thought on “Delete specific files in SharePoint

  1. Hello

    This command was amazing, but it stopped working. Displays the error “Find-PnPFile Attempted operation is prohibited because it exceeds the list view threshold”

    I tried searching on the internet, but I didn’t find a way around it, as it says there is a limit of 5000 items per page, but I didn’t find this argument within Find-PnPFile

Legg igjen en kommentar

Din e-postadresse vil ikke bli publisert. Obligatoriske felt er merket med *

I accept the Privacy Policy

Dette nettstedet bruker Akismet for å redusere spam. Lær om hvordan dine kommentar-data prosesseres.