PowerShell script to delete sharepoint large list in batch job

write-host

  1. Enter your configuration here

$siteUrl = “http://abc/SiteDirectory/test/”
$listName = “ErrorWarning”
$batchSize = 100

write-host “Opening web at $siteUrl…”

$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
$web = $site.OpenWeb()
write-host “Web is: $($web.Title)”
$q = New-Object Microsoft.SharePoint.SPQuery ;
$q.RowLimit = 100;

$list = $web.Lists[$listName];
write-host “List is: $($list.Title)”
$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);

while ($list.ItemCount -gt 0)
{
write-host “Item count: $($list.ItemCount)”
$coll = $list.GetItems($q);

$sbDelete = New-Object -TypeName “System.Text.StringBuilder”;
[void]$sbDelete.Append(“<?xml version=`”1.0`” encoding=`”UTF-8`”?><Batch>”)

$ids = @()
for ($i=0;$i -le $coll.Count;$i++)
{
$item = $coll[$i];
[void]$sbDelete.Append([string]::Format($command, $item.ID.ToString(), $item.File.ServerRelativeUrl));
$ids = $ids + $item.UniqueId;
}
$sbDelete.Append(“</Batch>”);

write-host

write-host “Sending batch…”

  1. We execute it

$result = $web.ProcessBatchData($sbDelete)

write-host “Emptying Recycle Bin…”

  1. We remove items from recyclebin

$web.RecycleBin.DeleteAll()

write-host

$list.Update()
}

write-host “Done.”

Advertisements