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

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!

In this article:

  • How to Delete All Documents in a Library in SharePoint Online?
  • SharePoint Online: Delete All Files in a Document Library using PowerShell
  • PowerShell to Delete All Files and Folders in SharePoint Online Document Library
  • PnP PowerShell to Delete All Files in SharePoint Online Document Library
  • Empty a SharePoint Online Document Library using PnP PowerShell

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

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

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.

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 AssembliesAdd-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 FolderFunction 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 FolderDelete-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!

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

#Load SharePoint CSOM AssembliesAdd-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

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 SiteConnect-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 recursivelyFunction 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 functionDelete-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 OnlineConnect-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 FileWrite-host -f Green "Number of Files Found:"$Files.CountForEach($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}

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 SiteConnect-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 FolderFunction 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 libraryEmpty-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 OnlineConnect-PnPOnline -Url $SiteURL -InteractiveGet-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.

Related Posts

SharePoint Online: Delete All Files in a Document Library using PowerShell (2024)
Top Articles
Repairs vs. Improvements - Rental Property - Clergy Financial Resources
Difference between OneDrive and ShareFile - GeeksforGeeks
Cold Air Intake - High-flow, Roto-mold Tube - TOYOTA TACOMA V6-4.0
Uca Cheerleading Nationals 2023
Part time Jobs in El Paso; Texas that pay $15, $25, $30, $40, $50, $60 an hour online
What is Mercantilism?
Asian Feels Login
Craigslist Cars And Trucks For Sale By Owner Indianapolis
Voorraad - Foodtrailers
Wellcare Dual Align 129 (HMO D-SNP) - Hearing Aid Benefits | FreeHearingTest.org
Ross Dress For Less Hiring Near Me
Here are all the MTV VMA winners, even the awards they announced during the ads
Nc Maxpreps
Bank Of America Appointments Near Me
AB Solutions Portal | Login
Costco in Hawthorne (14501 Hindry Ave)
Rubfinder
123 Movies Babylon
Tight Tiny Teen Scouts 5
Cincinnati Bearcats roll to 66-13 win over Eastern Kentucky in season-opener
Elizabethtown Mesothelioma Legal Question
Wisconsin Women's Volleyball Team Leaked Pictures
Paradise leaked: An analysis of offshore data leaks
Aucklanders brace for gales, hail, cold temperatures, possible blackouts; snow falls in Chch
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
Richland Ecampus
Marion City Wide Garage Sale 2023
Target Minute Clinic Hours
Lininii
Sf Bay Area Craigslist Com
Emily Katherine Correro
Teenbeautyfitness
Capital Hall 6 Base Layout
Metra Union Pacific West Schedule
Envy Nails Snoqualmie
Skroch Funeral Home
CVS Near Me | Somersworth, NH
National Insider Threat Awareness Month - 2024 DCSA Conference For Insider Threat Virtual Registration Still Available
159R Bus Schedule Pdf
Puretalkusa.com/Amac
ACTUALIZACIÓN #8.1.0 DE BATTLEFIELD 2042
Citibank Branch Locations In North Carolina
John M. Oakey & Son Funeral Home And Crematory Obituaries
Amy Zais Obituary
Caphras Calculator
40X100 Barndominium Floor Plans With Shop
Grace Family Church Land O Lakes
Hampton Inn Corbin Ky Bed Bugs
Twizzlers Strawberry - 6 x 70 gram | bol
Elizabethtown Mesothelioma Legal Question
login.microsoftonline.com Reviews | scam or legit check
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 6469

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.