A SharePoint library is a location on a site where you can upload, create, update, and collaborate on files with team members. To remove an empty folder from the library is difficult since we need to go to each and every library and identify whether it is empty or not. Then, we have to remove it from the library. To automate this process, I used Powershell scripting because it is easy to parse through each and every library using PNP library. So it is easy to identify and remove the empty folders in SharePoint library
Before you begin utilizing PowerShell to oversee SharePoint Online, ensure that the SharePoint Online Management Shell is installed. You can install the SharePoint Online Management Shell by downloading and running the SharePoint Online Management Shell. You only need to do this once for each computer from which you are running SharePoint Online PowerShell commands.
Connect to Site
Connect to SharePoint site using Connect-PnPOnline cmdlet. The required parameters are,
-UrlThe SharePoint site URL (Eg: https://hubflysoft.sharepoint.com/sites/Hubfly)
The following code snippet helps to connect SharePoint sites.
- $siteurl="https://<tenant-name>.sharepoint.com"
- Connect-PnPOnline -Url $siteurl

Get Web Instance using Get-PnPWeb
- $web = Get-PnPWeb
The Get-PnPWeb cmdlet actually has its own Recurse option, and you could use that if you want to rather than doing your own recursion.
Get User Context using Get-PnPContext
- $context = Get-PnPContext
The Get-PnPContext returns a Client Side Object Model context. This command is very handy and it returns the current context. You might need context because it might be the case you need to save the current context. By switching between two sites you need this.
Get folders from the library using Get-PnPFolder
- $folder = Get-PnPFolder -RelativeUrl "Shared Documents"

Join the conversation! Your thoughts help the community grow.