Fix “You have to delete all the items in this folder before you can delete the folder” Error in SharePoint Online

Problem: When trying to delete a folder with sub-folders and files, I got an error message “You have to delete all the items in this folder before you can delete the folder” in SharePoint Online or OneDrive.

You have to delete all the items in this folder before you can delete the folder

You may also see the “Request was cancelled by event received. If attempting to delete a non-empty folder, it’s possible that it’s on hold” error at times.

Request was cancelled by event received. If attempting to delete a non-empty folder, it's possible that it's on hold

Root Cause:

Usually, we don’t need to empty the folder before deleting it. However, If the site is on the preservation-retention policy or eDiscovery hold, we may get this error message. When the site is on hold, documents can be deleted, but we can’t delete a folder with files and sub-folders directly. This is how Preservation hold works to prevent data loss.

Solution for “You have to delete all the items in this folder before you can delete the Folder” Error:

Either you disable the Retention policy or eDiscovery Hold for the site from Office 365 Security and Compliance center as Global Administrator (and allow some time to take effect!), or as the error message says, delete all files and sub-folders inside the folder first! Deleting files from each folder can be time-consuming, So You can use “View in File Explorer” to delete a folder with files or PowerShell to make it easier.

SharePoint Online: Delete Folder with Files using PowerShell

This PowerShell script deletes all files and sub-folders of the given folder in SharePoint Online 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
}

More here: How to Empty a Folder in SharePoint Online using PowerShell?

If you have a larger library, The Get-PnPListItem cmdlet with FolderServerRelativeURL parameter may fail – even though you used “PageSize”. So, Here is the PowerShell script to delete everything from a given folder in SharePoint Online:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/mumbai"
$ListName ="Work"
$FolderServerRelativeURL = "/sites/mumbai/w/Arun Tiwari/New folder/*"

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -UseWebLogin
    $List = Get-PnPList $ListName
       
    #Get All Items from Folder in Batch
    $global:counter = 0;
    $ListItems = Get-PnPListItem -List $ListName -PageSize 2000 -Fields ID,FileDirRef,FileRef -ScriptBlock `
        { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
                "Getting Items from Folder '$FolderServerRelativeURL'" -Status "Getting Items $global:Counter of $($List.ItemCount)";}

    #Get List Items from the folder and Sort List Items based on Server Relative URL - Descending
    $ItemsFromFolder = $ListItems | Where {$_.FieldValues["FileDirRef"] -like $FolderServerRelativeURL } | Select-Object @{Name="ServerRelativeURL";Expression={$_.FieldValues.FileRef}}, ID | Sort-Object -Descending -Property ServerRelativeURL
    Write-host "Total Number of Items Found in the Folder:"$ItemsFromFolder.count
         
    #Delete List Items in Batch
    $Batch = New-PnPBatch
    ForEach ($Item in $ItemsFromFolder)
    {
        Remove-PnPListItem -List $ListName -Identity $Item.ID -Recycle -Batch $Batch
        Write-host "Item Queued for deletion:"$Item.ServerRelativeURL
    }
    Invoke-PnPBatch -Batch $Batch -Details

}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This error may happen when you have files checked out! Check them in all to fix: SharePoint Online: PowerShell to Bulk Check In All Documents

In conclusion, the error message “You have to delete all the items in this folder before you can delete the folder” can be resolved by simply deleting or moving the items within the folder. By following the steps outlined in this article, you can easily resolve this error and delete the folder as needed.

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!

5 thoughts on “Fix “You have to delete all the items in this folder before you can delete the folder” Error in SharePoint Online

  • I had some problems with these scripts. Either returning 0 files or having to run it on individual sub-folders.

    Here are some non PowerShell solutions to this:

    > Move folder/s to a SharePoint site without retention policies on – should be able to delete there. Moved files will also appear in original site’s Recycle bin, so clear the deleted files out there if required.

    > Sync SharePoint folder/library on Window File Explorer – delete files on WFE – ensure to stop OneDrive sync on OneDrive sync client app (blue cloud in Window’s notification area, by date/clock) before removing folders on WFE.

    > Temporarily remove policy on Teams site, delete files then reinstate policy on site. May not be an option for everyone (eg if you don’t have admin rights on Compliance centre).

    Reply
  • Unfortunately neither of these scripts worked correctly for me. The first deleted 1 file incorrectly (in the correct site, but not within the folder path I indicated in $FolderServerRelativeURL). The second script said 0 items were found, which is wrong.

    Reply
  • Hi I’m still having the same issue so could you help me?. it’s still saying “You have to delete all the items in this folder before you can delete the folder”

    Reply
  • Hi Salaudeen Rajack,

    when running script i get the following error after sometime:

    ErrorMessage ResponseCode Request
    ———— ———— ——-
    The operation has timed out. 500 https://domain.sharep…

    Can you please help

    Reply

Leave a Reply

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