Bulk delete items from SharePoint Document Library with Powershell - with filters

Wed, Jun 26, 2019 One-minute read

I recently posted some Powershell for bulk / batch emptying a SharePoint document library (https://www.matt-thornton.net/tech/sharepoint/bulk-delete-items-and-folders-from-sharepoint-document-library-using-powershell) which works nicely.

(As long as you remember that the Batch Delete XML syntax is incredibly fiddly and sensitive! Case is important and backticks are required to escape stuff.)

Anyway; it works great to empty an entire library, but you may prefer to just be tidying up really old stuff. Well, that’s what I was doing anyway, and therefore wanted to expand it a bit.

For instance, you might like to ‘delete anything older than 3 months.’ The way I approached this was to add a new param to the script which was the day limit (i.e., how many days it should look back) and make it optional:

param($url,$libraryName, $dayLimit)
 
if($null -eq $url -or $null -eq $libraryName)
{
write-host "Must provide params URL and LibraryName"
break
}
 
if($null -eq $dayLimit)
{
                $dayLimit = 90
}

So this allows the param and sets it to 90 if it’s not provided. And then secondly, add to our main detection query, a filter to use it:

 $q.Query = "<Where><Leq><FieldRef Name='Created' /><Value Type='DateTime'><Today OffsetDays='-$dayLimit' /></Value></Leq></Where>"   

That should be it!