SharePoint Online: Delete Empty Folders using PowerShell

Requirement: Delete Empty Folders in SharePoint Online Document Library using PowerShell

Delete Empty Folders in SharePoint Online using PowerShell

Are you facing an issue with a lot of empty folders in your SharePoint Online site? And, if you’re like me, you probably wondered if there was an easier way to do it. Because identifying and deleting them using the web browser by navigating to each folder would be cumbersome. But PowerShell offers a way to get rid of them quickly and easily. In this blog post, we will take a look at how to delete empty folders in SharePoint Online using PowerShell.

How to Find Empty Folders in SharePoint Online?

If a folder doesn’t have any file or sub-folder in it, it is considered empty. So, here is how we can find empty folders in SharePoint Online from the web user interface.

  • Navigate to the document library >> Click on “Edit Current View” from the Views drop-down.
  • Select “Folder Child Count” and “Item Child Count” columns and Click on OK. sharepoint online delete empty folders
  • Now, the view shows the number of items and the number of folders in the top-level of each folder.
    find empty folders in sharepoint online

PowerShell to Find Empty Folders in SharePoint Online:

This script scans each folder in the given document library and checks if the number of files and sub-folders equals ‘0’.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName="Documents"
  
#Get Credentials to connect
$Cred= Get-Credential
   
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
#Get the List
$List = $Ctx.Web.lists.GetByTitle($ListName)
 
#Define the CAML Query to get 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>"
 
#Get All List Items matching the query
$Folders = $List.GetItems($Query)
$Ctx.Load($Folders)
$Ctx.ExecuteQuery()
 
Write-host "Total Number of Empty Folders:"$Folders.count
 
#Loop through each List Item
ForEach($Folder in $Folders)
{ 
    Write-host $Folder.FieldValues.FileRef
}

This script lists all empty folders in all levels of the given library. However, when we delete an empty folder, its parent folder also becomes empty. (provided the parent folder has only one empty folder and no other files in it!).

SharePoint Online: PowerShell to Remove Empty Folders

This PowerShell script deletes all empty folders from a given SharePoint Online document library.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Delete-SPOEmptyFolders([Microsoft.SharePoint.Client.Folder]$Folder)
{
    #Get All Sub-Folders from the given Folder
    $SubFolders = $Folder.Folders
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()

    #Process Each Sub-Folder Recursively
    ForEach($SubFolder in $SubFolders)
    {
        #Exclude "Forms" and Hidden folders
        If(($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))) -and $SubFolder.Name -ne $RootFolder.Name)
        {
            #Call the function recursively
            Delete-SPOEmptyFolders $SubFolder
        }
    }

    #Get All Files and Sub-Folders from the Sub-folder
    $SubFolders = $Folder.Folders
    $Files = $Folder.Files
    $Ctx.Load($SubFolders)    
    $Ctx.Load($Files)
    $Ctx.ExecuteQuery()

    Write-host -f Yellow "Checking 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  
    }
}

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Migration Documents"

#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

    #Get the Root Folder of the Library
    $List = $Ctx.web.Lists.GetByTitle($LibraryName)
    $RootFolder = $List.RootFolder
    $Ctx.Load($RootFolder)
    $Ctx.ExecuteQuery() 

    #Call the function to delete empty folders from a document library
    Delete-SPOEmptyFolders $RootFolder
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

PnP PowerShell to Delete Empty Folders in SharePoint Online:

Let’s simplify the above script further with PnP PowerShell:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$DocumentLibraryName = "Documents"
 
#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)

#Get the web & folder
$Web = Get-PnPWeb
$List = Get-PnPList -Identity $DocumentLibraryName -Includes RootFolder

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)
    {
        #Delete the folder
        $ParentFolder = Get-PnPProperty -ClientObject $Folder -Property ParentFolder
        $ParentFolderURL = $ParentFolder.ServerRelativeUrl.Substring($Web.ServerRelativeUrl.Length)    
        Remove-PnPFolder -Name $Folder.Name -Folder $ParentFolderURL -Force -Recycle
        Write-Host -f Green ("Deleted Folder: '{0}' at '{1}'" -f $Folder.Name, $Folder.ServerRelativeURL)
    }

}
#Call the Function to Delete empty Folders
Delete-PnPEmptyFolder $List.RootFolder

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

4 thoughts on “SharePoint Online: Delete Empty Folders using PowerShell

  • Hi, i wonder if you can help me! I am trying to run this script but receiving the message below:

    Delete-PnPEmptyFolder : Cannot process argument transformation on parameter ‘Folder’. Cannot convert the “Microsoft.SharePoint.Client.Folder” value of type “Microsoft.SharePoint.Client.Folder” to type “Microsoft.SharePoint.Client.Folder”.
    At line:41 char:23
    Delete-PnPEmptyFolder $List.RootFolder
    ~~~~~~~~~~~~~~~~
    CategoryInfo : InvalidData: (:) [Delete-PnPEmptyFolder], ParameterBindingArgumentTransformationException
    FullyQualifiedErrorId : ParameterArgumentTransformationError,Delete-PnPEmptyFolder

    Reply
  • Muchísimas gracias.

    Me ha ayudado mucho.

    Reply
  • Warning! As it stands this deletes empty folders that only contain subfolders even if subfolders are not empty. To avoid this add “-and $SubFolders.Count -eq 0” in line 21.
    Change line:
    If($Files.Count -eq 0 -and $Folder.Name -ne $LibraryName -and $Folder.Name -ne “Document”)
    To:
    If($Files.Count -eq 0 -and $SubFolders.Count -eq 0 -and $Folder.Name -ne $LibraryName -and $Folder.Name -ne “Document”)

    Reply
    • Yes, That’s the intended behavior of this script! If any folders doesn’t have a file in it(even though it may have an empty folder), its considered empty!!

      Reply

Leave a Reply