SharePoint Online: Delete All Files and Sub-Folders from a Folder Recursively using PowerShell
Requirement: Empty a Folder in the SharePoint Online document library by deleting all its files and Sub-Folders recursively.
How to delete a folder with subfolders and files from SharePoint Online?
Deleting files and sub-folders in SharePoint Online can be done through the SharePoint user interface. To delete all files and sub-folders from a folder in SharePoint Online, follow these steps:
- Open your SharePoint Online site in the browser >> Navigate to the folder you want to delete.
- Select all files and sub-folders in the folder.
- Click the “Delete” button in the command bar or right-click and choose “Delete.”
- Confirm the deletion by clicking “Delete” in the confirmation dialog.
Deleting files and sub-folders is a fairly straightforward process, but if you have multiple files and sub-folders to delete, this process can become time-consuming. To automate this task, you can use PowerShell. Let’s explore how to delete all files and sub-folders from a folder in SharePoint Online using PowerShell recursively.
PowerShell to Delete All Files and Sub-Folders from a SharePoint Online Folder
While preparing for migration, I had to clear out some old data – So I needed to delete files and folders recursively from a SharePoint Online site. We can use PowerShell to delete files and folders recursively in SharePoint Online. This can be a great way to quickly clean up your site or delete large amounts of content.
Let’s delete a folder with subfolders and files from SharePoint Online:
#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 and Sub-folders of a given Folder
Function Empty-SPOFolder([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()
#delete all subfolders
Foreach($Folder in $SubFolders)
{
#Exclude "Forms" and Hidden folders
If( ($Folder.Name -ne "Forms") -and (-Not($Folder.Name.StartsWith("_"))))
{
#Call the function recursively to empty the folder
Empty-SPOFolder -Folder $Folder
#Delete the folder
$Ctx.Web.GetFolderById($Folder.UniqueId).Recycle() | Out-Null
$Ctx.ExecuteQuery()
Write-host -f Green "Deleted Folder:"$Folder.ServerRelativeUrl
}
}
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
}
#Variables
$SiteURL = "https://crescent.sharepoint.com/Sites/Marketing"
$ServerRelativeUrl= "/Sites/Marketing/Project Documents/2018"
Try {
#Get Credentials to connect
$Cred= Get-Credential
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Get the web from URL
$Web = $Ctx.web
$Ctx.Load($Web)
$Ctx.executeQuery()
#Get the Folder object by Server Relative URL
$Folder = $Web.GetFolderByServerRelativeUrl($ServerRelativeUrl)
$Ctx.Load($Folder)
$Ctx.ExecuteQuery()
#Call the function to empty Folder
Empty-SPOFolder $Folder
#Delete the given Folder itself
Write-host -f Green "Deleting Folder:"$Folder.ServerRelativeUrl
$Folder.Recycle() | Out-Null
$Ctx.ExecuteQuery()
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
This PowerShell script deletes all files, sub-folders of a folder and then deletes the given folder too.
PnP PowerShell to Empty a Folder in SharePoint Online:
With PnP PowerShell, we can easily delete all files and folders recursively instead of deleting them manually, one at a time. Here is the PnP PowerShell script to clear all files and sub-folders of a given folder in the SharePoint Online document library:
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$FolderSiteRelativeURL = "Shared Documents/2018"
#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)
#Get the web & folder
$Web = Get-PnPWeb
$Folder = Get-PnPFolder -Url $FolderSiteRelativeURL
#Function to delete all Files and sub-folders from a Folder
Function Empty-PnPFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
#Get the site relative path of the Folder
If($Web.ServerRelativeURL -eq "/")
{
$FolderSiteRelativeURL = $Folder.ServerRelativeUrl
}
Else
{
$FolderSiteRelativeURL = $Folder.ServerRelativeUrl.Replace($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 folder
Empty-PnPFolder -Folder $Folder
To delete a folder in the SharePoint Online document library, use: SharePoint Online: How to Delete a Folder using PowerShell?
Delete a folder with files in SharePoint Online
Can’t delete a folder in SharePoint Online due to retention policy? Here is how to remove all files and sub-folders from a folder:
- Connect to SharePoint Online using the Connect-PnPOnline cmdlet.
- Retrieve the contents of the folder using the Get-PnPListItem cmdlet.
- Delete all files and sub-folders in the folder using the Remove-PnPListItem cmdlet.
#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName ="Branding"
$FolderServerRelativeURL = "/sites/Marketing/Branding/2019"
Try {
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get All Items from Folder in Batch
$ListItems = Get-PnPListItem -List $ListName -FolderServerRelativeUrl $FolderServerRelativeURL -PageSize 2000 | Sort-Object ID -Descending
#Powershell to delete all files from a folder
ForEach ($Item in $ListItems)
{
Remove-PnPListItem -List $ListName -Identity $Item.Id -Recycle -Force
Write-host "Removed File:"$Item.FieldValues.FileRef
}
}
Catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
The above code may cause a threshold-exceeded issue on larger lists. How about deleting a large folder with its files and sub-folders in batches to avoid any potential list view threshold exceeded issue? Use this script to empty a folder in SharePoint Online:
#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName ="Branding"
$FolderServerRelativeURL = "/sites/Marketing/Branding/2019/*"
Try {
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
#Get All Items from Folder in Batch
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000 | Sort-Object ID -Descending
Write-host "Total Number of Items Found:"$ListItems.count
#Get List Items from the folder
$ItemsFromFolder = $ListItems | Where {$_.FieldValues.FileDirRef -like $FolderServerRelativeURL }
#Powershell to delete all files from a folder
ForEach ($Item in $ItemsFromFolder)
{
Remove-PnPListItem -List $ListName -Identity $Item.Id -Recycle -Force
Write-host "Removed Item:"$Item.FieldValues.FileRef
}
}
Catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
To delete multiple folders in SharePoint Online from a CSV file, use: Bulk Delete Folders from in SharePoint Online from a CSV using PowerShell?
Conclusion:
In conclusion, using PowerShell to delete all files and sub-folders from a folder in SharePoint Online is a powerful and efficient method for automating the task of cleaning up your SharePoint environment. By leveraging the capabilities of PowerShell, you can save time and ensure that your SharePoint environment remains organized and streamlined. However, it is important to use this method carefully and only after verifying that the files and folders to be deleted are not needed. Deleted files and folders in SharePoint Online are moved to the Recycle Bin and can be restored within a certain amount of time, so make sure to use these commands responsibly.
delete folder from onedrive for bulk users.
Hi,
I’m trying to delete large folders/subfolders by using the last script but I still get the threshold error on
Get-PnPListItem. Is there something else I’m missing here?
Thanks
Get-PnPListItem cmdlet with -FolderServerRelativeUrl parameter may cause list view threshold exceeded issue on larger lists and libraries with > 5000 items. So, use:
Might be a bit old to comment – I am testing the last script on this page (deleting a large folder with its files and sub-folders in batches). It did start and deleted my target folder but then continued on and started deleting other folders. Sounds like same issue Josh reported. Any thoughts?
Hi, I keep getting the following error:
Error: A parameter cannot be found that matches parameter name ‘FolderServerRela
tiveUrl’.
I have a document library called docs and a folder F2, trying to delete everything within F2 folder.
this is the script:
$SiteURL = “https://test.sharepoint.com/sites/dev-ardian”
$ListName =”docs”
$FolderServerRelativeURL = “/sites/site/docs/F2”
Try {
#Connect to PnP Online
Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)
#Get the web & folder
#Get All Items from Folder in Batch
$ListItems = Get-PnPListItem -List $ListName -FolderServerRelativeUrl $FolderServerRelativeURL -PageSize 2000 | Sort-Object ID -Descending
#Powershell to delete all files from folder
ForEach ($Item in $ListItems)
{
Remove-PnPListItem -List $ListName -Identity $Item.Id -Recycle -Force
Write-host “Removed File:”$Item.FieldValues.FileRef
}
}
Catch {
write-host “Error: $($_.Exception.Message)” -foregroundcolor Red
}
Hi Salaudeen,
What is the best way to have it limit the recursive folder depth that it deletes from. For example, I know if I go 3 levels deep and delete the files and folders at that level it will not hit the view limit threshold and will run a lot faster than deleting thousands of individual files and folders at the lowest levels.
Any advise is appreciated.
I figured it out, This was my code:
Thanks, this is a great script! One suggestion is to update it so that it works with MFA, like you have for the delete multiple folders from a CSV file script.
Sure, You can delete multiple folders from a CSV file! Post has been updated with a link to PowerShell script that bulk deletes folders from a CSV.
Thanks for your reply. I tried to run the script but it got all files and folder in my Document library deleted even after specifying folder to be deleted. Please kindly help out
Hello,
Thanks for the script. Is it possible to delete in batches for huge folder in order to avoid list view threshold error when deleting in SharePoint Online
Sure, Post has been appended with the script to delete all files and sub-folders from given folder!
Hi Salaudeen,
The script worked perfectly for me.
But how we can run this for multiple top level folders in the library? Is there any way we can read folder names from CSV file and delete accordingly.
Thanks..
Sure, Here you go: SharePoint Online: Bulk Delete Folders using PowerShell