Home » Office 365 » How to Remove Empty Folders in SharePoint Online – Step-by-Step Solution
Office 365, SharePoint ~ 7 Minutes Reading

How to Remove Empty Folders in SharePoint Online – Step-by-Step Solution

author
Published By Mohit Jha
admin
Approved By Admin
Calendar
Published On July 30th, 2024
Navigating through every SharePoint Online folder to find empty ones is a chore! In this guide, we will discuss ways to remove empty folders from the SharePoint Online site. Moreover, we will also discuss the manual method and automated methods to tackle this problem. Additionally, we will mention a precautionary step before deleting empty folders.

Creating files and folders is easy in SharePoint Online. Therefore, ending up with unnecessary empty files is common. Is your SharePoint Online library filled with empty folders? These unused folders clutter your space and make finding files a hassle. However, you can easily remove these empty folders, one question can arise how do I remove empty folders in SharePoint Online?  let’s Understand the reasons for deleting empty folders in SharePoint Online.

What are the  Possible Reasons To Remove Empty SharePoint Online Folders?

There can be many reasons for removing empty folders, here we are mentioning some of the reasons:

Enhanced File Management: Empty folders can clutter the SharePoint document library and make it complicated for users to find folders. Therefore, removing empty folders streamlines improves the overall user experience and results in better file management.
Enhanced Performance: A cluttered document library can lead to faster load times and better performance. Removing empty folders can improve the efficiency of search queries as there will be less number of items.
Easier Maintenance: Regularly removing empty folders helps keep the library organized and manageable, making it easier to maintain and update. Fewer folders mean less time spent managing folder structures and permissions.
Effective Storage Monitoring: While empty folders don’t take up significant storage space, cleaning them up can prevent unnecessary clutter and make it easier to monitor actual storage use.

Remove Empty Folders in SharePoint Online – Methods

There are two specific methods to delete empty folders in SharePoint Online:

Manual Method: In this method, we use the SharePoint interface to delete empty folders this is perfect for smaller tasks manually.

Power Automate: Leverage the Power Automate interface to create a flow for removing empty files and folders.

PowerShell Method: You can use PowerShell commands to remove empty folders which is ideal for the automatic deletion of bulk folders.

Delete Empty Folders Using the Manual Method

Step 1. Login to SharePoint Online>>Click on “edit the current view” from the views dropdown. 

Step 2. Add two columns folder child count and item child count.

Step 3. Identify which folder shows zero in both columns.

Step 4. Delete that identified folder.

After following these steps you can easily remove empty folders in SharePoint Online.

Remove Empty SharePoint Folders By Creating Flow

  • Step 1: Sign into Power Automate>>Click on “Create” in the left-hand menu>>Choose “Instant cloud flow” to start flow manually
  • Step 2: Click on “New step”>>Search for “SharePoint”>>Select the “Get files (properties only)” action from the SharePoint connector>>Choose the Site Address where your document library is located>>Select the Library Name>>Set the Folder Path to the root folder if you want to check all folders.
  • Step 3: Click on “New step”>>Select the “Apply to each” action to loop through the folders retrieved>>In the “Select an output from previous steps” field>> Select the output from the “Get files (properties only)” action.
  • Step 4: Inside the “Apply to each” step>> Add a “Condition” action to check if a folder is empty>>Use the “Get files ” action again to count items inside each folder.
  • Step 5: If the added condition is true >>add a “Send an HTTP request to SharePoint” action to delete the folder>>Set the HTTP request to use the SharePoint REST API for deletion.

Sample HTTP request to delete a folder:

Method: POST
Uri: _api/web/GetFolderByServerRelativeUrl('/sites/yoursite/Shared Documents/FolderToDelete')/recycle()
Headers:
- Accept: application/json;odata=verbose
- X-RequestDigest: (Use the Dynamic Content to get the Request Digest)

After creating the flow using these steps test and validate the flow.

Delete Empty Folders SharePoint Online PowerShell Method

By using Powershell you can easily remove empty folders in SharePoint Online. This is the automated method that can neglect the chances of false deleting.

Commands to Find the Empty Folders

#Load client-side object model assemblies 
Add-Type -Path " Enter the ‘Microsoft.SharePoint.Client.dll’ path"
Add-Type -Path "Enter the Microsoft.SharePoint.Client.Runtime.dll path"   
#Initial Parameters
$SiteURL = "Enter your SharePoint site URL"
$ListName="Enter SharePoint list name"  
#retrive credentials to connect
$Cred= Get-Credential
#setting up of ctx
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password) 
#retrive SharePoint list
$List = $Ctx.Web. lists.GetByTitle($ListName)
#CAML Query to retrieve empty folders
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery
$Query.ViewXml = "@
<View Scope='RecursiveAll'>
    <Query>
        <Where>
            <And>
                <And>
                    <Eq><FieldRef Name='ContentType' /><Value Type='Text'>Folder</Value></Eq>
                    <Eq><FieldRef Name='ItemChildCount' /> <Value Type='Counter'>0</Value></Eq>
                </And>
                <Eq><FieldRef Name='FolderChildCount' /> <Value Type='Counter'>0</Value></Eq>                   
            </And>
        </Where>
    </Query>
</View>"
#All List Items matching the CAML condition
$Folders = $List.GetItems($Query)
$Ctx.Load($Folders)
$Ctx.ExecuteQuery() 
Write-host "No. of empty folders:"$Folders. count 
#traverse through each list item
ForEach($Folder in $Folders)
{
    Write-host $Folder.FieldValues.FileRef
}

Commands to Delete the Empty Folders

#Load client-side object model assemblies

Add-Type -Path " Enter the ‘Microsoft.SharePoint.Client.dll’ path"
Add-Type -Path "Enter the Microsoft.SharePoint.Client.Runtime.dll path"
#Function for deleting empty folders
Function Delete-SPOEmptyFolders([Microsoft.SharePoint.Client.Folder]$Folder)
{
    #command to get all sub-folders
    $SubFolders = $Folder.Folders
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery() 
    #Process Each Sub-Folder 
    ForEach($SubFolder in $SubFolders)
    {
        #condition for form and hidden files
        If(($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))) -and $SubFolder.Name -ne $RootFolder.Name)
        {
            #recursive function call
            Delete-SPOEmptyFolders $SubFolder
        }
    }       
    #Get All Files 
    $SubFolders = $Folder.Folders
    $Files = $Folder.Files
    $Ctx.Load($SubFolders)   
    $Ctx.Load($Files)
    $Ctx.ExecuteQuery()
    Write-host -f Yellow "let's check if the folder is empty:" $Folder.serverRelativeURL
    #Delete Empty Folders
    If($SubFolders.Count -eq 0 -and $Files.Count -eq 0)
    {
        #Delete the folder
        $EmptyFolder=$Ctx.web.GetFolderByServerRelativeUrl($Folder.ServerRelativeUrl)
        $EmptyFolder.Recycle() | Out-Null
        $Ctx.ExecuteQuery()
        Write-host -f Green "`tDeleted Empty Folder:"$Folder.ServerRelativeUrl 
    }
} 
#initial parameters
$SiteURL = "ENTER YOUR SITE URL"
$LibraryName = "ENTER LIBRARY NAME" 
#Get Credentials to connect
$Cred = Get-Credential  
Try {
    #Setting up of Ctx
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
    #retrive the root folder 
    $List = $Ctx. web.Lists.GetByTitle($LibraryName)
    $RootFolder = $List.RootFolder
    $Ctx.Load($RootFolder)
    $Ctx.ExecuteQuery()
    #call delete function
    Delete-SPOEmptyFolders $RootFolder
}
catch {
    write-host "OOPS! ERROR: $($_.Exception.Message)" -foreground color Red
}

After applying all these commands in PowerShell you can successfully remove empty folders in SharePoint Online.

Considerations Before Removing Empty Folders in SharePoint Online

Before removing empty folders and following the above steps. Remember these methods require full concentration if any of these steps is done wrongly resulting in data loss or unnecessary deletion of important folders. To avoid this situation you can migrate or create a copy of the SharePoint site or folders. However, Microsoft doesn’t provide any direct method to migrate your SharePoint Online site. Therefore, you need to use vendor software to migrate your SharePoint site. 

In this case, we suggest you use the SharePoint Migration Tool as many professionals also recommend this tool. This software can automate the process of the SharePoint site to another site migration. Additionally, this tool has security features and the vendor doesn’t need to store your data to accomplish the migration task.on top of it provides SharePoint Online tenant-to-tenant migration.

Conclusion

To conclude, we have mentioned the necessary method to remove an empty folder in SharePoint Online. However,  all the necessary steps that are required to show the solution via Powershell and manual steps & precautionary steps can be taken before deleting folders are discussed.  Till now we have learned three methods a manual method and two automated methods, to perform removal with these methods requires technical knowledge.