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,


The SharePoint site URL (Eg: https://hubflysoft.sharepoint.com/sites/Hubfly)

The following code snippet helps to connect SharePoint sites.

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

The Get-PnPFolder returns the folder called ‘Shared Documents’ which is located in the root of the current web.

Get all subfolders and remove empty folders

Using the context we need to load all files, folders, and Parent folder like below code snippet

  1. $files = $folder.Files
  2. $context.Load($folder.Files)
  3. $context.Load($folder.Folders)
  4. $context.Load($folder.ParentFolder)
  5. $context.ExecuteQuery()

We can find the folder is empty by the following conditions,

  • Check if the files count is equal to zero
  • Check  if the folders count is equal to zero

And remove the empty folders using below PS script

I hope you learned how to remove empty folders and files in the SharePoint library programmatically using PnP PowerShell scripting. The operations mentioned above are tested on SharePoint Online environment. Feel free to leave a comment  below, if you need any assistance.