SharePoint Online: Delete All Files in a Document Library using PowerShell

Requirement: Delete all documents in library in SharePoint Online

How to Delete All Documents in Library in SharePoint Online?
At times you may want to delete multiple documents all at once. You can delete multiple files, folders and sub-folders from a SharePoint Online document library in few clicks:
  • Navigate to your SharePoint Online document library in browser, hover over header and click the check mark to select all files.
    sharepoint online delete all files in document library
  • Click on "Delete" button on the top link bar.
  •  In the Delete dialog box, confirm the delete by clicking "Delete" button
    sharepoint online delete all documents in library
  • You'll find the little status box appear in the upper top of the document library telling you that the item has been deleted.
    sharepoint online delete all files
Once all items are deleted from the document library, and the view is updated. The deleted files are moved to the site's recycle bin.
Tips: You can also use Explorer view to delete multiple files! Go to the library >> Click on "Open with Explorer" option from the Library's ribbon tab. Select and delete Files!

SharePoint Online: Delete All Files in Document Library using PowerShell
This PowerShell script deletes all files from a given library - without deleting any folders in it!
#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 from a given Folder
Function Delete-AllFilesFromFolder([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
                Delete-AllFilesFromFolder -Folder $Folder
            }
        }
    }
    Catch {
    write-host -f Red "Error:" $_.Exception.Message
    }
}

#Variables for Processing
$SiteURL = "https://crescenttech.sharepoint.com/sites/Marketing"
$LibraryRelativeURL = "/sites/Marketing/Shared Documents"

#Get Credentials to connect
$Cred = Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials

#Get the Root Folder of the Library
$RootFolder=$Ctx.Web.GetFolderByServerRelativeUrl($LibraryRelativeURL)
$Ctx.Load($RootFolder)

#Call the function to delete all Files from a Folder
Delete-AllFilesFromFolder -Folder $RootFolder 
Please note, These scripts uses "Recycle" method to send files to recycle bin. You can use "Delete" method to permanently delete files!

PowerShell to Delete All Files and Folders in SharePoint Online Document Library
If you want to delete all files and sub-folders in a library, use:
#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"

#Variables for Processing
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$LibraryRelativeURL = "/Sites/Marketing/Shared Documents"

Try {
    #Get Credentials to connect
    $Cred = Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials

    #Get the Library and Files
    $Folder=$Ctx.Web.GetFolderByServerRelativeUrl($LibraryRelativeURL)
    $Ctx.Load($Folder)
    $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
    $SubFolders = $Folder.Folders
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()
    Foreach($SubFolder in $SubFolders)
    {
        #Exclude "Forms" and Hidden folders
        If( ($SubFolder.Name -ne "Forms") -and (-Not($SubFolder.Name.StartsWith("_"))))
        {
            #Delete the folder
            $Folder.Folders.GetByUrl($SubFolder.ServerRelativeUrl).Recycle()| Out-Null
            Write-host -f Green "Deleted Folder '$($SubFolder.Name)' from '$($SubFolder.ServerRelativeUrl)'"
        }
        $Ctx.ExecuteQuery()
    }
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
If you want to delete a particular file, use: Delete Files in SharePoint Online using PowerShell

PnP PowerShell to Delete All Files in SharePoint Online Document Library
This PowerShell script deletes all files from all folders and sub-folders of the given document library. (doesn't deletes the folders, BTW!)
#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/icdocs"
$ListName = "Images"

#Connect to the Site
Connect-PnPOnline -URL $SiteURL -UseWebLogin

#Get the web & document Library
$Web = Get-PnPWeb
$List = Get-PnPList -Identity $ListName

#Function to delete all items in a folder - and sub-folders recursively
Function Delete-AllFilesFromFolder([Microsoft.SharePoint.Client.Folder]$Folder)
{
    #Get the site relative path of the Folder
    $FolderSiteRelativeURL = $Folder.ServerRelativeUrl.Replace($web.ServerRelativeUrl,"")

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

    #Process all Sub-Folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder
    Foreach($Folder in $SubFolders)
    {
        #Exclude "Forms" and Hidden folders
        If( ($Folder.Name -ne "Forms") -and (-Not($Folder.Name.StartsWith("_"))))
        {
            #Call the function recursively
            Delete-AllFilesFromFolder -Folder $Folder
        }
    }
}

#Get the Root Folder of the Document Library and call the function
Delete-AllFilesFromFolder -Folder $List.RootFolder
We can also use Move-PnPListItemToRecycleBin cmdlet to delete files and send them to the recycle bin.
#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$LibraryName = "Project Documents"
 
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get All Files from the document library - Exclude Folder Objects
$Files = Get-PnPListItem -List $LibraryName -PageSize 1000 | Where {$_["FileLeafRef"] -like "*.*"}
 
#Loop through each File
Write-host -f Green "Number of Files Found:"$Files.Count
ForEach($File in $Files)
{  
    Write-Host ("Deleting File '{0}' at {1}" -f $File["FileLeafRef"], $File["FileRef"])
    #Send File
    Move-PnPListItemToRecycleBin -List $LibraryName -Identity $File.Id -Force
}
SharePoint Online: Delete All Files in a Document Library using PowerShell SharePoint Online: Delete All Files in a Document Library using PowerShell Reviewed by Salaudeen Rajack on May 28, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.