In this delete all files in document library PowerShell script, we will learn about how we can delete all files from all document libraries in SharePoint online sites from a given date by passing From date and To date.
Delete all files in document library PowerShell (delete files in sharepoint): use cases
The PowerShell script can be used in the below scenario:
- Delete specific files from SharePoint on-premises library and SharePoint online library.
- Delete all files in the SharePoint document library from all document libraries.
- Delete all files from a SharePoint online site that were uploaded to all document libraries for the given dates.
Delete all files in document library: PowerShell script to delete all files from all document libraries on SharePoint online site
Using the below PowerShell script, we can delete all files from all document libraries in SharePoint Online from the given dates.
#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" cls $fileName = "File_Deleting_Report" #'yyyyMMddhhmm yyyyMMdd $enddate = (Get-Date).tostring("yyyyMMddhhmmss") #$filename = $enddate + '_VMReport.doc' $logFileName = $fileName +"_"+ $enddate+"_Log.txt" $invocation = (Get-Variable MyInvocation).Value $directoryPath = Split-Path $invocation.MyCommand.Path $directoryPathForLog=$directoryPath+"\"+"LogFiles" if(!(Test-Path -path $directoryPathForLog)) { New-Item -ItemType directory -Path $directoryPathForLog #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red } #$logPath = $directoryPath + "\" + $logFileName $logPath = $directoryPathForLog + "\" + $logFileName $isLogFileCreated = $False #DLL location $directoryPathForDLL=$directoryPath+"\"+"Dependency Files" if(!(Test-Path -path $directoryPathForDLL)) { New-Item -ItemType directory -Path $directoryPathForDLL } #DLL location $clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll" $clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll" Add-Type -Path $clientDLL Add-Type -Path $clientDLLRuntime #File Download location $directoryPathForFileDownloadLocation=$directoryPath+"\"+"Downloaded Files" if(!(Test-Path -path $directoryPathForFileDownloadLocation)) { New-Item -ItemType directory -Path $directoryPathForFileDownloadLocation #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red } #File Download location function Write-Log([string]$logMsg) { if(!$isLogFileCreated){ Write-Host "Creating Log File..." if(!(Test-Path -path $directoryPath)) { Write-Host "Please Provide Proper Log Path" -ForegroundColor Red } else { $script:isLogFileCreated = $True Write-Host "Log File ($logFileName) Created..." [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg) Add-Content -Path $logPath -Value $logMessage } } else { [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg) Add-Content -Path $logPath -Value $logMessage } } #Parameters $siteURL="https://globalsharepoint.sharepoint.com/sites/SharePointRND/" $listName="Documents" $fromDate="2019-12-08" $toDate="2019-12-12" $downloadLocation=$directoryPathForFileDownloadLocation; $userName = "Global-sharepoint@globalsharepoint.onmicrosoft.com" $password = "YourSPOPassWord" $securePassword= $password | ConvertTo-SecureString -AsPlainText -Force $batchSize =1000 #Parameters ends here. #Setup the Context $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL) $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $securePassword) <# $web = $ctx.Web $ctx.Load($web) $ctx.Load($web.Webs) $ctx.ExecuteQuery()#> #The below code is for root site $docLibraryColl=$ctx.Web.Lists $ctx.Load($docLibraryColl) $ctx.ExecuteQuery() foreach($oneList in $docLibraryColl) { if($oneList.BaseTemplate -eq "101" -and $oneList.BaseType -eq "DocumentLibrary" -and $oneList.Hidden -eq $False -and $oneList.IsCatalog -eq $False -and $oneList.IsApplicationList -eq $False) { #Get the List $list = $ctx.Web.Lists.GetByTitle($oneList.Title) $ctx.Load($list) $ctx.ExecuteQuery() $emptyString = "" #Define CAML Query to get Files from the list in batches $Query = New-Object Microsoft.SharePoint.Client.CamlQuery $startDateVar=$fromDate+"T13:35:58Z" #$startDate=Get-Date -Date $startDateVar; $endDateVar=$toDate+"T13:36:34Z" #$endDate=Get-Date -Date $endDateVar; $Query.ViewXml = "@ <View Scope='Recursive'> <Query> <Where> <And> <Geq> <FieldRef Name='Created' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>$startDateVar</Value> </Geq> <Leq> <FieldRef Name='Created' /> <Value IncludeTimeValue='TRUE' Type='DateTime'>$endDateVar</Value> </Leq> </And> </Where> </Query> </View>" $count =0 #Get List Items in Batches Do { $ListItems = $List.GetItems($Query) $Ctx.Load($ListItems) $Ctx.ExecuteQuery() $ListItems.Count #Update Postion of the ListItemCollectionPosition $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition $Query.ListItemCollectionPosition If ($ListItems.Count -eq 0) { Break } $fileCount=1; #Update List Item ForEach($Item in $ListItems) { try { $Ctx.Load($Item.File) $Ctx.ExecuteQuery() $Item.File.DeleteObject(); $Ctx.ExecuteQuery() Write-Host $Item.File.Name "has been deleted successfully" -BackgroundColor DarkGreen } catch { $ErrorMessage = $_.Exception.Message +$file.Name Write-Host $ErrorMessage -BackgroundColor Red Write-Log $ErrorMessage } } Write-Host "=============================================================" Write-Host $count Write-Host "=============================================================" }While ($Query.ListItemCollectionPosition -ne $null) } }
Prerequisites to execute this script: delete all files in document library PowerShell
Need to place the below two DLLs in your script directory “Dependency Files” folder as below:
Script execution test: delete all files in document library PowerShell (delete files in sharepoint) demo
Execute delete all files in document library PowerShell script as below:

Summary: Delete all files in document library PowerShell (delete files in PowerShell)
Here in this script, we have learned the below:
- How to delete a file from the SharePoint document library programmatically.
- Delete file from SharePoint document library using PowerShell.
- Delete all files from a SharePoint online site that were uploaded to all document libraries for the given dates.
See Also: SharePoint online PowerShell
You may also like the below SharePoint Online PowerShell tutorials:
- Office 365: Getting started with SharePoint PnP PowerShell – installation
- Get hub sites and associated sites using PnP PowerShell
- SharePoint Online Automation – O365 – Download files from a document library using PowerShell CSOM
- SharePoint Online Automation – O365 – Create multiple items in a list using PowerShell CSOM
- SharePoint Online Automation – O365 – Upload files to document library using PowerShell CSOM
- SharePoint Automation: PowerShell script to get remote server information
- SharePoint Online Automation – O365 – Send email from SharePoint online Using CSOM PowerShell script
- SharePoint Online Automation – O365 – Update document library metadata using PowerShell CSOM
- Introduction to SharePoint information architecture

1 comments on “Safely delete all files in document library PowerShell: Delete All Files from document library for the given date – Office 365”