SharePoint Online: Delete Empty Folders using PowerShell
Requirement: Delete Empty Folders in SharePoint Online Document Library 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 by using Item Child Count (Number of items in the root level of the folder, and NOT the total of all the items in all the subfolders.) and Folder Child Count (The number of subfolders in the root level of the folder).
- 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.
- Now, the view shows the number of items and the number of folders in the top-level of each folder.
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+1)
#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+1)
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
Summary
In conclusion, deleting empty folders in SharePoint Online can be a time-consuming task, but with the use of PowerShell, it can be automated. By using the script provided in this article, you can quickly and easily remove any empty folders in your SharePoint Online environment, keeping your site organized and up-to-date.
Getting “Get-PnPFolderItem : The attempted operation is prohibited because it exceeds the list view threshold” error when running on a large library. Is there a way to make this work on libraries with hundreds of thousands of files and folders?
Thanks Salaudeen !
Do you know, for the PnP PowerShell script, how its possible to specify some folders in the library,
instead of scanning all folders ?
Thanks a lot !
Instead of calling the Function with “$List.RootFolder”, use something like this:
#Get a Specific Folder
$Folder = Get-PnPFolder -Url “/sites/sales/Shared Documents/New”
#Call the function to scan and delete empty folders from a given folder
Delete-PnPEmptyFolder $Folder
Hello, I am facing the following error whenever I am trying to run the script:
“Remove-PnPFolder : Server relative urls must start with SPWeb.ServerRelativeUrl”
Can anyone help or suggest?
Make sure you have the New PnP.PowerShell module installed! (and all the legacy versions of SharePointPnPPowerShellOnline Uninstalled); How to Install PnP PowerShell Module for SharePoint Online?
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
Try: Close and Re-Open PowerShell ISE!
MuchÃsimas gracias.
Me ha ayudado mucho.
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”)
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!!