Clearning up Large Lists and Recycle Bin with PowerShell

If you want to dump large lists quickly you can use batch delete script mentioend below.  Deleing items one by one in loop will take a lot of time.  Even if you delete the items they will get stuck in site collection recyle bin.  You can modify the script as needed.

Add-PSSnapin Microsoft.SharePoint.powerShell -ErrorAction SilentlyContinue 
$sitecollectionUrl = https://portal.contoso.com
$siteCollection = New-Object Microsoft.SharePoint.SPSite($sitecollectionUrl)
$web = $siteCollection.OpenWeb('Web') 

$list = $web.Lists["Logging List"] 

write-host("Logging List has : $list.ItemCount Items.") -ForegroundColor Yellow
write-host("Recyle Bin has : $siteCollection.RecycleBin.Count Items.") -ForegroundColor Yellow 

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

$listItems = $list.Items
foreach ($item in $listItems)
{
    if($item -ne $null){$batchXml.Append([System.String]::Format($command, $item.ID.ToString())) | Out-Null;$itemCount++;}
} 

$batchXml.Append("</Batch>");
$itemCount; 

$web.ProcessBatchData($batchXml.ToString()) | Out-Null;Write-Host("Starting to Clear Site Collection Recyle Bin: $siteCollection.RecycleBin.Count") -ForegroundColor Yellow 
$siteCollection.RecycleBin.DeleteAll();
Write-Host("Cleared Log List and Site Collection Recyle Bin.")
$web.Dispose()
$siteCollection.Dispose()
 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s