Delete files with Batch deletion

This code allows you to delete many files from a document library in the most efficient way… that I found anyway… this code will generate a batch deletion XML command and execute it. i used this code to delete 1 million files and it took less than a day to run without locking up tables in the DB. the deletion is permanent and do not save copies in the recycle bin.  use very carefully !!!

 

clear
Add-PSSnapin Microsoft.SharePoint.Powershell -ea SilentlyContinue
$w = Get-SPWeb <your site url>
$list = $w.Lists[“<your list name>”]
$query = New-Object Microsoft.SharePoint.SPQuery;
$query.ViewAttributes = “Scope=’Recursive'”;
$query.RowLimit = 20000;

$createdOnInternalFieldName = ‘Created’
$caml = ‘<Where><Leq><FieldRef Name=”{0}” /><Value Type=”DateTime”><Today OffsetDays=”-1462″ /></Value></Leq></Where><OrderBy><FieldRef Name=”ID” Ascending=”True”/></OrderBy>’-f $createdOnInternalFieldName
$query.Query = $caml

for ($num = 1 ; $num -le 50 ; $num++){
write-host “loop itteration : “$num

$len = 0;
$listItems = $list.GetItems($query)
$len = $listItems.Count

if( $len -gt 0 ){

[System.Text.StringBuilder]$sbDelete = New-Object “System.Text.StringBuilder”;
$sbDelete.Append(“<?xml version=`”1.0`” encoding=`”UTF-8`”?><ows:Batch OnError=`”Return`”>”);
$command = [System.String]::Format( “<Method><SetList>{0}</SetList><SetVar Name=`”ID`”>{1}</SetVar><SetVar Name=`”Cmd`”>Delete</SetVar>”, $list.Id, “{0}” );

foreach ($item in $listItems)
{
if ($item -ne $null){
$sbDelete.Append([System.String]::Format($command, $item.ID.ToString())) ;
$sbDelete.Append(“<SetVar Name=`”owsfileref`”>”+ $list.ParentWeb.Url+”/”+$item.Url +”</SetVar>”);
$sbDelete.Append(“</Method>”);
}
}
$sbDelete.Append(“</ows:Batch>”);
#write-host $sbdelete

$web = Get-SPWeb <your site url>
$web.ProcessBatchData($sbDelete.ToString());
}# end if
}# end for

Leave a Reply

Your email address will not be published. Required fields are marked *