Thursday, February 18, 2016

Deleting all the items from a large list in SharePoint

Server Object Model:
string command = String.Format("<Method><SetList Scope=\"Request\">{0}</SetList><SetVar Name=\"ID\">{{0}}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar><SetVar Name=\"owsfileref\">{{1}}</SetVar></Method>", list.ID);
 
   SPQuery q = new SPQuery();
   q.RowLimit = 100;


   while (list.ItemCount > 0)
   {

    SPListItemCollection coll = list.GetItems(q);

    StringBuilder strval = new StringBuilder();
    strval .Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

    Guid[] ids = new Guid[coll.Count];
    for (int i=0;i<coll.Count;i++)
    {
     SPListItem item = coll[i];
     strval .Append(string.Format(command, item.ID.ToString(), item.File.ServerRelativeUrl));
     ids[i] = item.UniqueId;
    }
    strval .Append("</Batch>");
web.ProcessBatchData(strval .ToString());
 web.RecycleBin.Delete(ids);

    list.Update();
   }
  }

Powershell Script:


$siteUrl = "http://peakfinders/"
$listName = "Employee"
$batchSize = 100
$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
$web = $site.OpenWeb()
$list = $web.Lists[$listName];
while ($list.ItemCount -gt 0)
{
  $batch = "<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>"
  $i = 0

  foreach ($item in $list.Items)
  {
    $i++
    write-host "`rProcessing ID: $($item.ID) ($i of $batchSize)" -nonewline
    $batch += "<Method><SetList Scope=`"Request`">$($list.ID)</SetList><SetVar Name=`"ID`">$($item.ID)</SetVar><SetVar Name=`"Cmd`">Delete</SetVar><SetVar Name=`"owsfileref`">$($item.File.ServerRelativeUrl)</SetVar></Method>"
    if ($i -ge $batchSize) { break }
  }
  $batch += "</Batch>"
   write-host "Sending batch..."
  $result = $web.ProcessBatchData($batch)
  write-host "Emptying Recycle Bin..." 
  $web.RecycleBin.DeleteAll()
  write-host
  $list.Update()

}



No comments:

Post a Comment