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

Requirement: Delete all documents in a library in SharePoint Online.

SharePoint Online document libraries can quickly become cluttered with unnecessary or outdated files. When it comes time to clean house, manually deleting files one by one is tedious and time-consuming. Fortunately, with PowerShell, you can swiftly delete all files in a SharePoint Online document library with just a few lines of script.

In this article, I will walk through how to use PowerShell to connect to SharePoint Online and delete all files in a specified document library. Whether you need to make room for a batch of new uploads or want to archive a document library before the new year, deleting all files from SharePoint Online is quick and painless with PowerShell. Follow along as we clean the slate on a SharePoint document library in just minutes!

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:

  1. 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
  2. Click on the “Delete” button on the top link bar.
  3. On the Delete dialog box, confirm the delete operation by clicking the “Delete” button.sharepoint online delete all documents in library
  4. You’ll find the little status box appears at 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 SharePoint site’s recycle bin.

Please note that 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

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

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

Did you know 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 “DeleteObject” 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 this mass delete script:

#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. (Don’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
            $ParentFolderURL = $FolderSiteRelativeURL.TrimStart("/")
            Remove-PnPFolder -Name $SubFolder.Name -Folder $ParentFolderURL -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
}

A Faster Way to Delete All Items from a Document Library

While the above methods work perfectly, deleting all items from larger libraries takes a lot of time. So, here is the ScriptBlock PowerShell command to batch-delete items faster.

$SiteURL = "https://crescent.sharepoint.com/sites/papers"
$ListName = "Preservation Hold Library"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

Get-PnPList -Identity $ListName | Get-PnPListItem -PageSize 100 -ScriptBlock {
    Param($items) Invoke-PnPQuery } | ForEach-Object { $_.Recycle() | Out-Null
}

This script removes all Files and folders from the given document library! To delete the document library, use: How to Delete a document library in SharePoint Online using PowerShell?

In conclusion, deleting all files from a SharePoint Online document library can be a challenging and time-consuming process. However, using PowerShell can make this process more efficient and straightforward. With the script provided in this guide, you can easily delete all files in a SharePoint Online document library in just a few steps.

Can deleted files be permanently removed from SharePoint Online?

Deleted files in SharePoint Online are retained for a certain period of time (usually 93 days) before they are permanently deleted. Deleted items from the site Recycle bin are moved to the site collection Recycle Bin, where a site collection administrator can restore them. If an item is deleted from the site collection Recycle Bin or exceeds the retention time, it is permanently deleted!

How long are deleted files retained in SharePoint Online?

Deleted files in SharePoint Online are retained for 93 days after being deleted from their original location. When a file is deleted from a SharePoint Online site, it goes into the site Recycle Bin, where it is retained for 93 days unless someone deletes it or empties the Recycle Bin. If the file is deleted within 93 days from the site Recycle Bin (or 1st stage recycle bin), it goes into the site collection Recycle Bin (or 2nd stage recycle bin). After the retention period of 93 days in total with both stages of the recycle bin, deleted files are permanently deleted and cannot be restored.

How do I delete a library template in SharePoint Online?

Assuming you have Edit permissions, you can delete any document library or list template by clicking on the Settings Gear, choosing “Site Information”, and then clicking “Site Settings”. Now, click on List Templates under Galleries, Find, and then delete the template you wish! Alternatively, You can use PowerShell to delete a document library template in SharePoint Online

How do I delete all items from a SharePoint list?

To delete all items from a SharePoint list, you can use the “Edit in Grid view” or “Quick Edit” view to select all items and then delete them in bulk. Alternatively, you can use PowerShell commands to delete all items from the list.

How do I delete multiple versions of documents in SharePoint?

To delete multiple versions of documents in SharePoint Online, go to the document library and select the files you want to delete versions of. Then, Right-click on the File and select “Version History.” From there, you can delete all previous versions of a document by clicking on “Delete all versions”. Alternatively, You can use PowerShell to Delete all Previous versions of documents in SharePoint Online.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

10 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
    • Sure! Use the following line to get all files of specific extension and then proceed with the rest of the script to delete them (Assuming you want to delete all .txt files from the library):
      $Files = Get-PnPListItem -List $LibraryName -PageSize 1000 | Where {$_[“FileLeafRef”] -like “*.txt”}

      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
      • It does not. the -scriptblock part will refuse to run. The part before that works OK and does list all folders and items.

        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

Your email address will not be published. Required fields are marked *