Remove Empty Folders in SharePoint Online to Clear & Delete Files
When businesses purchase an Office 365 subscription SharePoint online is a strong reason for doing so. So when their SharePoint fills up with empty folders and admins are unable to remove empty folders in SharePoint online this is a cause for concern. It means users will face issues in collaboration, document management, and more.
So it becomes extremely important to clear out the folders that don’t have any content in them. Not to worry as we have multiple methods to achieve this along with a tool that prevents the biggest cause of empty folders from occurring. First up we have the Power Automate style of detecting and destroying the contentless folders in SharePoint.
Delete Empty Folders in Sharepoint Document Library using Power Automate
We are going to use what’s called a Flow. Log on to the Power Automate portal or select PowerAutomate from the Microsoft 365 apps menu.
Step-1. On the main PowerAutomate screen click on the Instant Flow option.
Step-2. Give an appropriate name, and be sure to choose “Manually trigger a flow”. Once done click on Create.
Step-3. Inside the Edit mode, you need to add additional actions so click on the + New step button.
Step-4. Look for the SharePoint HTTP there pick the “Send an HTTP request to SharePoint”
In the Site Address property add your site where you want this flow to run. Set the Method property as GET.
Step-5. Uri needs to resemble the following “_api/web/GetFolderByServerRelativeUrl(‘/sites/YourSiteName/YourDocumentLibraryName’)/”.
Step-6. At last fill both the Headers properties with the following values, the Key should be “accept”, and the value should be “application/json;odata=nometadata”.
Step-7. Create a Filter array to filter the output from the previous step. Use the expression body(‘GetFolders’)?[‘value’]. Click on “Edit in advanced mode” and put the following expression thin the free space: @and(equals(item()?[‘ItemCount’], 0), not(equals(item()[‘Name’], ‘Forms’))).
This may look confusing at first but it’s actually quite simple let’s break down the code. The first part i.e. till the 0 digit checks if the item count exceeds zero or not the next part is a safety feature to prevent “Forms” deletion.
Step-8. Add another action of the same category i.e “Send an HTTP request to SharePoint”. This time choose “Apply to each” in the action column.
Step-9. Put your Site Address, in the Method and select DELETE. Use the Same Uri property as Step 5. At the end of the Uri include this Expression “(items(‘ForEach_Folder’)[‘Name’])”. Save and deploy the Flow.
Remove Empty Folders in SharePoint Online Via PowerShell Scripts
The following PowerShell script is tested to work in an actual SharePoint environment. However, we recommend that admins exercise caution.
#-----------------------------------------------------------[Configuration]------------------------------------------------------------ # SharePoint URL $siteUrl = '<Your-URL>' # Site URL $site = 'sites/lab01' # Library name $libraryName = 'Duplicates' # Set test mode $whatIf = $true # Set force mode # Only set to true after you test it. Script WON'T ask for confirmation before deleting the file $force = $false #-----------------------------------------------------------[Functions]------------------------------------------------------------ # Function to delete empty folders recursively Function Delete-PnPEmptyFolder([Microsoft.SharePoint.Client.Folder]$Folder) { $FolderSiteRelativeURL = $Folder.ServerRelativeUrl.Substring($Web.ServerRelativeUrl.Length) # 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 Delete-PnPEmptyFolder -Folder $SubFolder } } # Get all files & Reload Sub-folders from the given Folder $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder if ($Files.Count -eq 0 -and $SubFolders.Count -eq 0) { $ParentFolder = Get-PnPProperty -ClientObject $Folder -Property ParentFolder $ParentFolderURL = $ParentFolder.ServerRelativeUrl.Substring($Web.ServerRelativeUrl.Length) if ($whatIf -ne $true) { Write-Host "Removing folder:" $Folder.Name "in" $ParentFolderURL -ForegroundColor Red Remove-PnPFolder -Name $Folder.Name -Folder $ParentFolderURL -Force:$force -Recycle } else { Write-Host "Empty folder:" $Folder.Name "in" $ParentFolderURL -ForegroundColor Red } } } # Function to connect to SharePoint Online Function Connect-ToSharePointOnline($url) { Connect-PnPOnline -Url $url -UseWebLogin if (-not $?){ Write-Host "Failed to connect to SharePoint Online" -ForegroundColor Red exit } } #-----------------------------------------------------------[Execution]------------------------------------------------------------ # Construct the full UR $url = $siteUrl + '/' + $site # Connect to SharePoint Online Connect-ToSharePointOnline -url $url # Cleanup empty folders $Web = Get-PnPWeb $List = Get-PnPList -Identity $libraryName -Includes RootFolder Delete-PnPEmptyFolder -Folder $List.RootFolder
The workings of this script are as follows:
It connects to a user-given SharePoint Online site, navigates to a specified document library, and recursively deletes empty folders within that library. Admins get two options a safe mode ($whatIf) for testing and a force mode ($force) for actual deletions.
Clear Empty Folders in SharePoint Portal on Your Own
- Log in to the SharePoint web app.
- Open the Site where the Empty folders are present.
- Select Documents from the left side Pane
- Take your cursor over the Empty folder right-click and Delete.
Note: This is not a permanent removal the Empty file continues to persist in the Recycle bin until the end of the retention period. If you want to do a hard delete go to the recycle bin and repeat the same step.
Also Read: Learn to move and copy files with metadata tags in SharePoint Online
Sometimes organizations may even set up a secondary recycle bin. If your organization follows this practice then it adds another layer to clear out the content-less folders from SharePoint. Apart from this, we have a method for a more technically oriented audience as well.
Now that we have covered all the methods of deleting empty folders let’s see the major reasons why such entities accumulate inside a SharePoint Site in the first place.
Why do Admins Need to Remove Empty Folders in SharePoint Online Regularly?
There are many different reasons why the SharePoint library becomes populated with countless empty folders. These serve no purpose other than to clutter the system and end up diminishing the productivity of workers. It becomes increasingly hard for users to reach the file that contains the actual data. So it is only natural to ask what led to their formation. There are a few top contenders.
Also Read: Compare SharePoint On-Premise VS SharePoint Online for your Organization
Your organization underwent a merger or acquisition and onboarded a bunch of new faces. With them, they brought a ton of SharePoint site data too. Due to an inferior migration mechanism, you suffer one or more of these:
- Incomplete transfer: Files fail to migrate due to technical issues.
- Permission hiccups: Permissions don’t translate correctly, hiding files from some users.
- Version mismatch: Only specific file versions get transferred.
- Filtering gone wrong: Migration filters exclude intended files.
- User mix-ups: Accidental deletion or movement during manual migration.
As we saw ineffective strategy is the most common reason for this problem. To make sure that this does not happen again we present you the SysTools SharePoint Migration tool. Designed to handle all scenarios this tool ensures that all your source side data gets placed correctly on the target.
Load > Select > Validate > Map > Migrate is the 5-step approach with which the tool proves itself on. So next time a SharePoint site arrives use this tool and forget about the empty folder problem.
Conclusion
Here we gave users a foolproof plan to remove empty folders in SharePoint Online. For that users can use any of the strategies, like the SharePoint portal, Power Automate, or PowerShell commands. Depending on the technical proficiency admins can choose the most suitable method. Apart from that, we have also suggested a tool that prevents content-less folders from appearing on your SharePoint site in a post-migration environment.