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

I recently posted some Powershell for bulk / batch emptying a SharePoint document library (http://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:

<code>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
}</code>

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:

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

That should be it!

Be the first to comment

Leave a Reply

Your email address will not be published.


*