SharePoint Powershell script: delete all items from recycle bin to prevent timeout

Imagine you have a BIG enterprise SharePoint installation, with BIG files filling up Recycle bin over time. You would want to eventually free up database space by deleting these entries from the database entirely. SharePoint has two recycle bin stages: first is just a flag in a database, so this operation is instant. The other operation can be time consuming in the situation where total amount of data is > 15-20 GB. This may lead the UI operation to time out (30s period)

What we can do is to delete them from the object model. Here is the old-way PowerShell script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[System.Reflection.Assembly]::Load(“Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)

# If actual item count in your recycle bin is > 1000 you will have to rerun this script
$rowlimit = 1000;

$siteUrl = read-host “Enter site URL “
$site = new-object Microsoft.SharePoint.SPSite(“$siteUrl”);
 
$query = new-object Microsoft.SharePoint.SPRecycleBinQuery;
$query.ItemState = “SecondStageRecycleBin”;
$query.RowLimit = $rowlimit;
 
$itemcoll = $site.GetRecycleBinItems($query);
foreach ($item in $itemcoll) {
    $id = $item.ID;
    write-host -nonewline “Deleting “ $item.Title ” … “;
    $itemcoll.Delete($id);
    write-host “Done”;
}

Leave a Reply

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