SharePoint Online: Delete All Files in a Document Library using PowerShell

Requirement: Delete all documents in a library in SharePoint Online

How to Delete All Documents in a Library in SharePoint Online?

In SharePoint Online, you may occasionally need to delete all the files in a document library. For example, if you’re importing a large number of documents into the library or if you’re cleaning up old files. Let’s see how you can quickly delete all documents in a library.

Tips: You can also use Explorer view to delete multiple files! Go to the library >> Click on “Open with Explorer” option from the Library’s ribbon tab. Select and delete Files!

You can delete multiple files, folders, and sub-folders from a SharePoint Online document library in a few clicks:

  • Navigate to your SharePoint Online document library in the browser, hover over the header, and click the check mark to select all files.
    sharepoint online delete all files in document library
  • Click on the “Delete” button on the top link bar.
  • On the Delete dialog box, confirm the delete operation by clicking the “Delete” button sharepoint online delete all documents in library
  • You’ll find the little status box appears in the upper top of the document library, telling you that the item has been deleted.
    sharepoint online delete all files

Once all items are deleted from the document library, the list view is updated, and deleted files are moved to the site’s recycle bin.

Please note, You have to make sure no file is checked out to other users before deleting them from the library. Otherwise, You may get a “File is checked out or locked” error. Here is another post on checking in all files from SharePoint Online Library: SharePoint Online: Bulk Check In All Checked Out Files using PowerShell

File is checked out or locked

At times, you may want to delete multiple documents all at once. Are you tired of manually deleting files in SharePoint Online? Here’s a PowerShell script to automate the process.

SharePoint Online: Delete All Files in Document Library using PowerShell

Did you know that you can use PowerShell to delete all files in a SharePoint Online document library? This can be useful if you want to clean up a library before moving or deleting it. This article will show you how to do this using PowerShell. This PowerShell script deletes all files from a given library – without deleting any folders in it!

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Function to Delete all files from a given Folder
Function Delete-AllFilesFromFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
    Try {
        #Get All Files from the Folder
        $Ctx = $Folder.Context
        $Files = $Folder.Files
        $Ctx.Load($Files)
        $Ctx.ExecuteQuery()

        #Iterate through each File in the Root folder
        Foreach($File in $Files)
        {
            #Delete the file
            $Folder.Files.GetByUrl($File.ServerRelativeUrl).Recycle() | Out-Null
            Write-host -f Green "Deleted File '$($File.Name)' from '$($File.ServerRelativeURL)'"
        }
        $Ctx.ExecuteQuery()

        #Process all Sub Folders of the given folder
        $SubFolders = $Folder.Folders
        $Ctx.Load($SubFolders)
        $Ctx.ExecuteQuery()
        Foreach($Folder in $SubFolders)
        {
            #Exclude "Forms" and Hidden folders
            If( ($Folder.Name -ne "Forms") -and (-Not($Folder.Name.StartsWith("_"))))
            {
                #Call the function recursively
                Delete-AllFilesFromFolder -Folder $Folder
            }
        }
    }
    Catch {
    write-host -f Red "Error:" $_.Exception.Message
    }
}

#Variables for Processing
$SiteURL = "https://Crescent.sharepoint.com/sites/Marketing"
$LibraryRelativeURL = "/sites/Marketing/Shared Documents"

#Get Credentials to connect
$Cred = Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials

#Get the Root Folder of the Library
$RootFolder=$Ctx.Web.GetFolderByServerRelativeUrl($LibraryRelativeURL)
$Ctx.Load($RootFolder)

#Call the function to delete all Files from a Folder
Delete-AllFilesFromFolder -Folder $RootFolder 

Please note that these scripts use the “Recycle” method to send files to the recycle bin. You can use the “Delete” method to delete files permanently!

PowerShell to Delete All Files and Folders in SharePoint Online Document Library

If you want to delete all files and sub-folders in a library, use:

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Variables for Processing
$SiteURL = "https://Crescent.sharepoint.com/sites/marketing"
$LibraryRelativeURL = "/Sites/Marketing/Shared Documents"

Try {
    #Get Credentials to connect
    $Cred = Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Get the Library and Files
    $Folder=$Ctx.Web.GetFolderByServerRelativeUrl($LibraryRelativeURL)
    $Ctx.Load($Folder)
    $Files = $Folder.Files
    $Ctx.Load($Files)
    $Ctx.ExecuteQuery()

    #Iterate through each File in the Root folder
    Foreach($File in $Files)
    {
        #Delete the file
        $Folder.Files.GetByUrl($File.ServerRelativeUrl).Recycle() | Out-Null
        Write-host -f Green "Deleted File '$($File.Name)' from '$($File.ServerRelativeURL)'"
    }
    $Ctx.ExecuteQuery()

    #Process all Sub Folders
    $SubFolders = $Folder.Folders
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()
    Foreach($SubFolder in $SubFolders)
    {
        #Exclude "Forms" and Hidden folders
        If( ($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))))
        {
            #Delete the folder
            $Folder.Folders.GetByUrl($SubFolder.ServerRelativeUrl).Recycle()| Out-Null
            Write-host -f Green "Deleted Folder '$($SubFolder.Name)' from '$($SubFolder.ServerRelativeUrl)'"
        }
        $Ctx.ExecuteQuery()
    }
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}

If you want to delete a particular file, use: Delete Files in SharePoint Online using PowerShell

PnP PowerShell to Delete All Files in SharePoint Online Document Library

How do I bulk delete files in SharePoint Online? Well, This PowerShell script deletes all files from all folders and sub-folders of the given document library. (doesn’t delete the folders, BTW!)

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/icdocs"
$ListName = "Images"

#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Interactive

#Get the web & document Library
$Web = Get-PnPWeb
$List = Get-PnPList -Identity $ListName

#Function to delete all items in a folder - and sub-folders recursively
Function Delete-AllFilesFromFolder($Folder)
{
    #Get the site relative path of the Folder
    If($Folder.Context.web.ServerRelativeURL -eq "/")
    {
        $FolderSiteRelativeURL = $Folder.ServerRelativeUrl
    }
    Else
    {        
        $FolderSiteRelativeURL = $Folder.ServerRelativeUrl.Replace($Folder.Context.web.ServerRelativeURL,[string]::Empty)
    }

    #Get All files in the folder
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File
    
    #Delete all files
    ForEach ($File in $Files)
    {
        Write-Host ("Deleting File: '{0}' at '{1}'" -f $File.Name, $File.ServerRelativeURL)
        
        #Delete Item
        Remove-PnPFile -ServerRelativeUrl $File.ServerRelativeURL -Force -Recycle
    }

    #Process all Sub-Folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder
    Foreach($Folder in $SubFolders)
    {
        #Exclude "Forms" and Hidden folders
        If( ($Folder.Name -ne "Forms") -and (-Not($Folder.Name.StartsWith("_"))))
        {
            #Call the function recursively
            Delete-AllFilesFromFolder -Folder $Folder
        }
    }
}

#Get the Root Folder of the Document Library and call the function
Delete-AllFilesFromFolder -Folder $List.RootFolder

We can also use the Move-PnPListItemToRecycleBin cmdlet to delete files and send them to the recycle bin.

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Project Documents"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get All Files from the document library - Exclude Folder Objects
$Files = Get-PnPListItem -List $LibraryName -PageSize 1000 | Where {$_["FileLeafRef"] -like "*.*"}

#Loop through each File
Write-host -f Green "Number of Files Found:"$Files.Count
ForEach($File in $Files)
{  
    Write-Host ("Deleting File '{0}' at {1}" -f $File["FileLeafRef"], $File["FileRef"])
    #Send File
    Move-PnPListItemToRecycleBin -List $LibraryName -Identity $File.Id -Force
}

Empty a SharePoint Online Document Library using PnP PowerShell

How about emptying a document library by deleting all files, folders, and sub-folders from it?

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Documents"
 
#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Interactive
 
#Get the web & Root folder of the library
$Web = Get-PnPWeb
$Library = Get-PnPList -Identity $LibraryName -Includes RootFolder
$RootFolder = $Library.RootFolder

#Function to delete all Files and sub-folders from a Folder
Function Empty-PnPFolder($Folder)
{
    #Get the site relative path of the Folder
    If($Folder.Context.web.ServerRelativeURL -eq "/")
    {
        $FolderSiteRelativeURL = $Folder.ServerRelativeUrl
    }
    Else
    {        
        $FolderSiteRelativeURL = $Folder.ServerRelativeUrl.Replace($Folder.Context.web.ServerRelativeURL,[string]::Empty)
    }
 
    #Delete all files in the Folder
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File
    ForEach ($File in $Files)
    {
        #Delete File
        Remove-PnPFile -ServerRelativeUrl $File.ServerRelativeURL -Force -Recycle
        Write-Host -f Green ("Deleted File: '{0}' at '{1}'" -f $File.Name, $File.ServerRelativeURL)       
    }
 
    #Process all Sub-Folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder
    Foreach($SubFolder in $SubFolders)
    {
        #Exclude "Forms" and Hidden folders
        If(($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))))
        {
            #Call the function recursively
            Empty-PnPFolder -Folder $SubFolder
 
            #Delete the folder
            Remove-PnPFolder -Name $SubFolder.Name -Folder $FolderSiteRelativeURL -Force -Recycle
            Write-Host -f Green ("Deleted Folder: '{0}' at '{1}'" -f $SubFolder.Name, $SubFolder.ServerRelativeURL)
        }
    }
}
 
#Call the function to empty document library
Empty-PnPFolder -Folder $RootFolder

While the above script works perfectly fine with smaller libraries with < 5000 files, on bigger libraries, it gets “Get-PnPFolderItem : The attempted operation is prohibited because it exceeds the list view threshold.” error as the Get-PnPFolderItem can’t handle large lists and libraries. So, here is the alternate script to empty a document library by deleting all files and folders in it faster with the PnP Batch method:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Inventory"
$ListName = "Archive"

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive
    $List =  Get-PnPList $ListName
    $ItemCount =  $List.ItemCount
    If($ItemCount -eq 0) { Write-host "Document Library is Already Empty!" -f Yellow; Break}

    #Get All Items from the Library
    $global:counter = 0
    $ListItems = Get-PnPListItem -List $ListName -PageSize 500 -Fields ID -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete `
            ($global:Counter / $ItemCount * 100) -Activity "Getting Items from List" -Status "Getting Items $global:Counter of $($ItemCount)"}
    Write-Progress -Activity "Completed Getting Items from Library $($List.Title)" -Completed

    #Sort List Items based on Server Relative URL - Descending
    $SortedItems = $ListItems | Select-Object @{Name="ServerRelativeURL";Expression={$_.FieldValues.FileRef}}, ID | Sort-Object -Descending -Property ServerRelativeURL
    
    #Delete List Items in the Batch
    $Batch = New-PnPBatch
    ForEach ($Item in $SortedItems)
    {
        Remove-PnPListItem -List $ListName -Identity $Item.ID -Recycle -Batch $Batch
        #Write-host "Deleted Item:"$Item.ServerRelativeURL
    }
    Invoke-PnPBatch -Batch $Batch -Details

    Write-host -f Green "All Items in the Library deleted Successfully!"
 }
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This script removes all Files and folders from the given document library!

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

8 thoughts on “SharePoint Online: Delete All Files in a Document Library using PowerShell

  • Hey, this site is amazingly useful! Thank you! I am trying to iterate through a specific document library and delete all files with specific extensions from all folders in that libary? I have found your scripts to iterate through and list all files, but not one that can delete specific files while iterating through! Can you point me in the correct direction?

    Reply
  • I solved this issue my site’s library had an extra space in between two words that I only picked up on by looking at the url to find the %20%20. Fixed that and this works like a charm

    Reply
  • Thank you for sharing! When I try to run the script i get the error: “Error: Exception calling “ExecuteQuery” with “0” argument(s): “File Not Found.”” Any idea what is going wrong?

    Reply
  • This site has been a godsend. For the last script (PNP for 5k+ items) I keep getting a “Invoke-PnPBatch : A task was canceled.”
    I’ve captured the error and done a Get-PNPException to get more information out of the stacktrace…..but it seems there’s very little to go off. Any ideas as to why the task would cancel itself? It seems to throw a nonsuccess while iterating (get to: 78, 36, 51) but doesn’t specify exactly why.

    Reply
  • Does this circumvent the 5000 limit list view theshold when deleting files in bulk?

    Reply
  • Thank you , this is so usefull.

    Do you have any suggesstion for if we have a csv file with full link to file need to delete and powershell can import them / auto spit link and fill them to $SiteURL and $LibraryRelativeURL tp process the deletion ?

    Appriciated.

    Reply

Leave a Reply