I am working on a powershell script to delete files in a specific folder in SharePoint 2013.

We do not have SharePoint online so the operation must be done with Rest API and from powershell.

Can anyone help?

  • share the current script
    – vipmaa
    Mar 11, 2020 at 16:21

2 Answers 2


A caml query will be enough to make the script delete files in a specific folder according to date.

$site = new-object Microsoft.SharePoint.SPSite("site url") 
$web = $site.rootweb 
$list = $web.Lists["library name"]

$query=new-object Microsoft.SharePoint.SPQuery 
            <FieldRef Name="Created" />
            <Value IncludeTimeValue="TRUE" Type="DateTime">2020-02-20</Value>

$query.Query=$caml | Write-Output
$query.Folder = $list.RootFolder.SubFolders["folder name"];
write-host $query
write-host $items.Name
$folderItemsTotal = $items.Count;
for($x=$folderItemsTotal-1;$x -ge 0; $x--)

Reference: https://social.technet.microsoft.com/Forums/office/en-US/c8b6f647-c9f1-475f-b773-f5e0fb754887/sharepoint-2010-powershell-script-to-delete-files-by-last-modified-date?forum=sharepointadminprevious


I think you can use the below script for your need, this will take fromDate and ToDate as a parameters which will scan through all documents within that range of dates and delete all files from those date. For your scenario you can give the FromDate as 60 days back and ToDate as current date.

This script has been developed in PowerShell CSOM object model, so this will fit both in SharePoint online and SharePoint on-premise.

#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"

$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  

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


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)  
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   

$userName = "[email protected]"
$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

  #The below code is for root site


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)
$emptyString = ""
#Define CAML Query to get Files from the list in batches
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery

#$startDate=Get-Date -Date $startDateVar; 
#$endDate=Get-Date -Date $endDateVar;

$Query.ViewXml = "@
    <View Scope='Recursive'>
            <FieldRef Name='Created' />
            <Value IncludeTimeValue='TRUE' Type='DateTime'>$startDateVar</Value>
            <FieldRef Name='Created' />
            <Value IncludeTimeValue='TRUE' Type='DateTime'>$endDateVar</Value>

$count =0

#Get List Items in Batches

    $ListItems = $List.GetItems($Query)

    #Update Postion of the ListItemCollectionPosition
    $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition

    If ($ListItems.Count -eq 0) { Break }


    #Update List Item
    ForEach($Item in $ListItems)




             Write-Host $Item.File.Name "has been deleted successfully" -BackgroundColor DarkGreen

            $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)



For details execution of the above script, please refer the below article :

SharePoint Online: Delete All Files from document library for the given date – PowerShell CSOM

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.