Deleting empty folders in Sharepoint Online library using Powershell CSOM

Introduction

Below is the script needed to get all empty folders in a SharePoint Online library and delete them. 

Prerequisites

To run it you need to provide two params:

  1. Site's URL
  2. Library's Name

Script

<#
DESCRIPTION
This script can be useful to search for empty folders and delete them, in a library located on a Sharepoint Online tenant
You need to know 2 mandatory parameters: 
    - $SiteCollectionUrl     : the URL for the site collection
    - LibraryName           : the name of the destination library
      
CopyRight
This script can be use as it is or can be changed based on your needs. For more details please feel free to contact me
Romeo Donca, April 2017
romeodonca@outlook.com
http://www.romeodonca.ro
#>
 
param(
[Parameter(Mandatory=$true,HelpMessage="The site collection URL")][string]$SiteCollectionUrl,
[Parameter(Mandatory=$true,HelpMessage="The name of the library")][string]$LibraryName
)
Add-Type -Path "your_path\Microsoft.SharePoint.Client.dll" 
Add-Type -Path "your_path\Microsoft.SharePoint.Client.Runtime.dll" 
#$SiteCollectionUrl = Read-Host -Prompt "Enter site collection URL: ";
#$LibraryName = Read-Host -Prompt "Provide library's name ";
#$SiteCollectionUrl = "https://romeodonca.sharepoint.com";
#$LibraryName = "Folders";
#$folderRelativeUrl =$LibraryName+"/" 
$folders_list=@()
 
$global:cred = Get-Credential
Connect-MsolService -Credential $global:cred -ErrorAction SilentlyContinue
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteCollectionUrl)
$cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.username, $cred.Password)  
$ctx.Credentials = $cred
$rootWeb = $ctx.Web
$ctx.Load($rootWeb)
$ctx.ExecuteQuery()
  
$folder = $rootWeb.GetFolderByServerRelativeUrl($rootWeb.ServerRelativeUrl + $folderRelativeUrl)
$ctx.Load($folder)
$ctx.ExecuteQuery()
 
Function GetAllSubFolders([Microsoft.SharePoint.Client.Folder] $fld,     [Microsoft.SharePoint.Client.ClientContext] $ctx)
{
    $files = $fld.Files
    $ctx.Load($fld.Files)
    $ctx.Load($fld.Folders)
    $ctx.ExecuteQuery()
  
    if ($fld.Files.Count -eq 0 -and (($fld.Name -notmatch 'Document') -and ($fld.Name -notmatch $LibraryName )))
    {
        $folders_list += $fld.Name+","+$fld.ServerRelativeUrl
    }
    foreach($subFolder in $fld.Folders)
    {
        GetAllSubFolders $subFolder $ctx
    }
    return $folders_list
}
cls
Write-Host "`nLooking for empty folders. Please wait...`n"
$folders_list =GetAllSubFolders $folder $ctx
if ($folders_list.Count -gt 0)
{
    Write-Host "`nThe empty folders are:" -BackgroundColor White -ForegroundColor Red
    foreach ($Folder in $folders_list)
    {
      Write-Host "Folder name: "$folder.split(",")[0] "`nPath:        " $folder.split(",")[1]"`n"
    }
 
    $deleting = Read-Host "Would you like to delete them? (Y/N)"
    if ($deleting.ToUpper() -eq "Y")
    {
        foreach ($Folder in $folders_list)
        {
            "We delete the folder: "+$folder.split(",")[0] + "`npath: "+   $folder.split(",")[1]+"`n"
            $foldertodelete = $rootWeb.GetFolderByServerRelativeUrl($folder.Split(',')[1])
            $ctx.Load($foldertodelete)
            $foldertodelete.DeleteObject()
            $ctx.ExecuteQuery()
        }
        Write-Host "`nAll folders have been deleted!`n" -BackgroundColor White -ForegroundColor Red
    }
}
else
{
    cls
    Write-Host "`nNo empty folders!`n" -BackgroundColor White -ForegroundColor Red
}

Credit

The main post can be found here.