SharePoint Online: Delete All Files and Sub-Folders from a Folder Recursively using PowerShell

Requirement: Empty a Folder in SharePoint Online document library by deleting all its files and Sub-Folders recursively.
Delete All Files and Sub-Folders from a Folder Recursively using PowerShell

PowerShell to Delete All Files and Sub-Folders from a SharePoint Online Folder
#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 to Delete all files and Sub-folders of a given Folder
Function Empty-SPOFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
    Try {
        #Get All Files from the Folder
        $Ctx = $Folder.Context
        $Files = $Folder.Files
        $Ctx.Load($Files)
        $Ctx.ExecuteQuery()
 
        #Iterate through each File in the Root folder
        Foreach($File in $Files)
        {
            #Delete the file
            $Folder.Files.GetByUrl($File.ServerRelativeUrl).Recycle() | Out-Null
            Write-host -f Green "Deleted File '$($File.Name)' from '$($File.ServerRelativeURL)'"
        }
        $Ctx.ExecuteQuery()
 
        #Process all Sub Folders of the given folder
        $SubFolders = $Folder.Folders
        $Ctx.Load($SubFolders)
        $Ctx.ExecuteQuery()
        Foreach($Folder in $SubFolders)
        {
            #Exclude "Forms" and Hidden folders
            If( ($Folder.Name -ne "Forms") -and (-Not($Folder.Name.StartsWith("_"))))
            {
                #Call the function recursively to empty the folder
                Empty-SPOFolder -Folder $Folder

                #Delete the folder
                $Ctx.Web.GetFolderById($Folder.UniqueId).Recycle() | Out-Null
                $Ctx.ExecuteQuery()
                Write-host  -f Green "Deleted Folder:"$Folder.ServerRelativeUrl
            }
        }
    }
    Catch {
    write-host -f Red "Error:" $_.Exception.Message
    }
}

#Variables
$SiteURL = "https://crescent.sharepoint.com/Sites/Marketing"
$ServerRelativeUrl= "/Sites/Marketing/Project Documents/2018"

Try {
    #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 web from URL
    $Web = $Ctx.web
    $Ctx.Load($Web)
    $Ctx.executeQuery()

    #Get the Folder object by Server Relative URL
    $Folder = $Web.GetFolderByServerRelativeUrl($ServerRelativeUrl)
    $Ctx.Load($Folder)
    $Ctx.ExecuteQuery() 

    #Call the function to empty Folder
    Empty-SPOFolder $Folder

    #Delete the given Folder itself
    Write-host  -f Green "Deleting Folder:"$Folder.ServerRelativeUrl
    $Folder.Recycle() | Out-Null
    $Ctx.ExecuteQuery() 
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
} 
This PowerShell script deletes all files, sub-folders of a folder and then deletes the given folder too.

PnP PowerShell to Empty Folder in SharePoint Online: 
Here is the PnP PowerShell script to clear all files and sub-folders of a given folder in SharePoint Online document library.
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$FolderSiteRelativeURL = "/Shared Documents/2018"

#Connect to the Site
Connect-PnPOnline -URL $SiteURL -Credentials (Get-Credential)

#Get the web & folder
$Web = Get-PnPWeb
$Folder = Get-PnPFolder -Url $FolderSiteRelativeURL

#Function to delete all Files and sub-folders from a Folder
Function Empty-PnPFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
    #Get the site relative path of the Folder
    $FolderSiteRelativeURL = $Folder.ServerRelativeUrl.Replace($web.ServerRelativeUrl,"")

    #Delete all files in the Folder
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File
    ForEach ($File in $Files)
    {
        #Delete File
        Remove-PnPFile -ServerRelativeUrl $File.ServerRelativeURL -Force -Recycle
        Write-Host -f Green ("Deleted File: '{0}' at '{1}'" -f $File.Name, $File.ServerRelativeURL)        
    }

    #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
            Empty-PnPFolder -Folder $SubFolder

            #Delete the folder
            Remove-PnPFolder -Name $SubFolder.Name -Folder $FolderSiteRelativeURL -Force -Recycle
            Write-Host -f Green ("Deleted Folder: '{0}' at '{1}'" -f $SubFolder.Name, $SubFolder.ServerRelativeURL)
        }
    }
}

#Call the function to empty folder
Empty-PnPFolder -Folder $Folder
SharePoint Online: Delete All Files and Sub-Folders from a Folder Recursively using PowerShell SharePoint Online: Delete All Files and Sub-Folders from a Folder Recursively using PowerShell Reviewed by Salaudeen Rajack on August 21, 2018 Rating: 5

1 comment:

  1. Hi Salaudeen,

    The script worked perfectly for me.
    But how we can run this for multiple top level folders in the library? Is there any way we can read folder names from CSV file and delete accordingly.

    Thanks..

    ReplyDelete

Please Login and comment to get your questions answered!

Powered by Blogger.