Wednesday, November 11, 2020

Delete a certain number of items SharePoint List Powershell Script

Due to the closure of "the blog TechNet" I transfer all my articles in the blog :)

To delete a fixed number of items in the list of WSS, SharePoint server without putting them in the Recycle Bin, this is very convenient, since the cleaning of the Recycle Bin takes a certain amount of time for the Site Collection Administrator.
This script is easy to use after the migration or backup of the lists / libraries in which you need to delete a certain number of items.

Pre-requisites:
1.PowerShell 2.0 and higher
2.WSS or SharePoint server 2007, 2010, 2013, 2016, 2019.

Powershell script:
#Load System.Reflection.Assembly WSS or SharePoint server 2007 only
[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Publishing, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
#PSSnapin SharePoint server 2010, 2013, 2016, 2019
if(!(Get-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction:SilentlyContinue)) 
{ 
    Add-PsSnapin Microsoft.SharePoint.PowerShell 
}
#Enter your parametrs here site, listname, count elements
$siteUrl = "http://sharepoint/sites/Department"
$listName = "Main"
$batchSize = 1000
$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
$web = $site.OpenWeb()
write-host "Web is: $($web.Title)"
$list = $web.Lists[$listName];
write-host "List is: $($list.Title)"
while ($list.ItemCount -gt 0)
{
  write-host "Item count: $($list.ItemCount)"
  $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>"
  $result = $web.ProcessBatchData($batch)
  write-host "Emptying Recycle Bin..."
  $web.RecycleBin.DeleteAll()
  write-host
  $list.Update()
}

Happy Coding!

No comments:

Post a Comment