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 which has sub-folders and files, got an error message "You have to delete all the items in this folder before you can delete the folder" in SharePoint Online.
You have to delete all the items in this folder before you can delete the folder

Root Cause:
Usually, we don't need to empty the folder before we delete it. However, If the site is on the preservation "On-Hold" policy, 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: Either you disable the 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! You can use "View in File Explorer" or PowerShell too 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.
#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 -UseWebLogin
      
    #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
}
More here: How to Empty a Folder in SharePoint Online using PowerShell?

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

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.