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

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 Files and Sub-Folders from the Folder
    $Files = $Folder.Files
    $SubFolders = $Folder.Folders
    $Ctx.Load($Files)
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()

    #Process Each Sub-Folders recursively
    ForEach($SubFolder in $SubFolders)
    {
        Delete-SPOEmptyFolders $SubFolder
    }
    
    #Delete Empty Folders
    If($Files.Count -eq 0 -and $Folder.Name -ne $LibraryName -and $Folder.Name -ne "Document")
    {
        #Delete the folder
        $EmptyFolder=$Ctx.web.GetFolderByServerRelativeUrl($Folder.ServerRelativeUrl)
        $EmptyFolder.Recycle() | Out-Null
        $Ctx.ExecuteQuery()
        Write-host -f Green "Deleted 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
}
SharePoint Online: Delete Empty Folders using PowerShell SharePoint Online: Delete Empty Folders using PowerShell Reviewed by Salaudeen Rajack on September 18, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.