Remove Empty Folders in SharePoint Online

After merging duplicate folders in SharePoint Online I needed to remove the empty folders. This is something we can do as well with PowerShell and PnP.

# SharePoint url
$siteUrl = 'https://lazyadmin.sharepoint.com/'

# Site url
$site = 'sites/lab01'

# Library name
$libraryName = 'Duplicates'

# Set test mode
$whatIf = $true

# Set force mode
# Only set to true if you have fully tested it. Script WON'T ask for confirmation before deleting the file
$force = $false

#-----------------------------------------------------------[Functions]------------------------------------------------------------

#src https://www.sharepointdiary.com/2018/09/sharepoint-online-delete-empty-folders-using-powershell.html
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)    

		if ($whatIf -ne $true)
		{
			#Delete the folder
			Write-Host "Remove folder:" $Folder.Name "in" $ParentFolderURL -ForegroundColor Red
			Remove-PnPFolder -Name $Folder.Name -Folder $ParentFolderURL -force:$force -Recycle
		}
		else
		{
			Write-host $parentFolder
			Write-Host "Empty folder:" $Folder.Name "in" $ParentFolderURL -ForegroundColor Red
		}
    }
}

#-----------------------------------------------------------[Execution]------------------------------------------------------------

# Login 
$url = $siteUrl + '/' + $site
Connect-PnPOnline -Url $url -UseWebLogin

# Cleanup empty folders
$Web = Get-PnPWeb
$List = Get-PnPList -Identity $libraryName -Includes RootFolder

Delete-PnPEmptyFolder $List.RootFolder

The script will go through all folders recursively. If the folder is empty then it will delete it. If you set the WhatIf variable to true at the top of the script, it will only show which folders it would delete. This way you can test the script before actually running it.

Delete folders based on name

If you only need to delete folders based on their name, for example, a folder that ends with *(1), then you can change the last part of the delete function to:

    If ($Files.Count -eq 0 -and $SubFolders.Count -eq 0)
    {
		if ($Folder.Name -like "*(1)") {
		
			#Delete the folder
			$ParentFolder = Get-PnPProperty -ClientObject $Folder -Property ParentFolder
			$ParentFolderURL = $ParentFolder.ServerRelativeUrl.Substring($Web.ServerRelativeUrl.Length)    

			if ($whatIf -ne $true)
			{
				#Delete the folder
				Write-Host "Remove folder:" $Folder.Name "in" $ParentFolderURL -ForegroundColor Red
				Remove-PnPFolder -Name $Folder.Name -Folder $ParentFolderURL -force:$force -Recycle
			}
			else
			{
				Write-host $parentFolder
				Write-Host "Empty folder:" $Folder.Name "in" $ParentFolderURL -ForegroundColor Red
			}
		}
    }

You can find the original version of the script here at Sharepointdairy.com. I only made a couple of small changes to the script. You can also get the full script here at my Github.

12 thoughts on “Remove Empty Folders in SharePoint Online”

  1. I’m using PnP 1.10.0, but am receiving this error message when I run the Script :

    Remove-PnPFolder : Server relative urls must start with SPWeb.ServerRelativeUrl

    any ideas appreciated 🙂

    A.

  2. Hi Dan,
    I’ve also started getting that same error recently…
    It seems Microsoft has once again changed something… and my posted solution above:
    i.) authenticate with azure, and ii) update powershell) above no longer resolves it..

    I haven’t had time to resolve yet… I read somewhere that the new PowerShell v7 doesn’t yet work with PNP commands (might over time?); but I am running v5.x – so I concluded MS were meddling in the background, and time would resolve… hence I parked the matter.

    I’d be interested if others have found the solution…

    • I have just tested the script again, using PNP version 1.8 and the script runs fine on my side.
      What is the result of


      # Login
      $url = $siteUrl + '/' + $site
      Connect-PnPOnline -Url $url -UseWebLogin

      $Web = Get-PnPWeb
      Get-PnPList -Identity $libraryName -Includes RootFolder | select -ExpandProperty RootFolder

  3. I need to only delete the *(1) folders and any subfolders as long as they have no files. We have empty folders in the structure we must keep so I cannot delete all empty folders. Any help appreciated on how to modify to check folder name for *(1) then verify all child folders are empty and delete the parent (or all children up to and including parent).

  4. I’m getting the error:
    Cannot convert the “Microsoft.SharePoint.Client.Folder”
    too, my script hasn’t changed and used to work… Microsoft must have changed something… does anyone have the solution?

  5. Hi, I am trying to use this script however I am receiving this error message:

    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:72 char:23
    + Delete-PnPEmptyFolder $List.RootFolder
    + ~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidData: (:) [Delete-PnPEmptyFolder], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Delete-PnPEmptyFolder

Leave a Comment

0 Shares
Tweet
Pin
Share
Share