Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
PowerShell to delete SharePoint list items in batch mode.
function DeleteListItems{
Deletes SharePoint List Items in batch
Deleted SharePoint List items in batch and provide sleep between batch. By default, it will delete all List Items.
You can delete List Items based on the CAML Query input parameter.
Mandatory. SharePoint List Url to be deleted. For example:
Optional. Batch Size per deletion request. For example if you specify 2000, and your list contains 10.000 items, then the
application will execute 5 deletion request with 2000 items deletion per request. Default: 2000
Optional. Valid CAML Query to specify deletion criteria. Default: "<Where><Geq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Geq></Where>"
Parameters above
Version: 1.1
Author: Riwut Libinuko
Creation Date: 29/12/2015
Last Update: 11/03/2018
DeleteListItems -ListUrl
Param (
[string]$camlQuery = "<Where><Geq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Geq></Where>"
$spSite = new-object Microsoft.SharePoint.SPSite($listUrl)
$spWeb = $spSite.OpenWeb()
$list = $spWeb.GetList($listUrl)
Write-host "Intializing SharePoint object for $listUrl"
Write-host "Deleting items in $listUrl with in $batchSize per batch"
$query = New-Object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = $batchSize
$query.Query = $camlQuery
$itemCount = 0
$listId = $list.ID
$command = [System.String]::Format( "<Method><SetList>{0}</SetList><SetVar Name=`"ID`">{1}</SetVar><SetVar Name=`"Cmd`">Delete</SetVar></Method>", $listId, "{0}" )
[System.Text.StringBuilder]$batchXml = New-Object "System.Text.StringBuilder"
$batchXml.Append("<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>")
$listItems = $list.GetItems($query)
$query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
Write-Host "Preparing" -NoNewline
if($listItems.Count -gt 0) {
foreach ($item in $listItems)
if($item -ne $null){
$batchXml.Append([System.String]::Format($command, $item.ID.ToString())) | Out-Null;
Write-Host "." -NoNewline
Write-Host "."
Write-Host "Total $($listItems.Count) will be deleted.."
Write-host "Sending batch command"
$web.ProcessBatchData($batchXml.ToString()) | Out-Null
Start-Sleep -Seconds 2 #Need to give some fresh air
while ($query.ListItemCollectionPosition -ne $null)
$span=[System.timespan]($endtime - $starttime)
Write-host "Deleting total $itemCount item(s) in $timeSpent seconds"

This comment has been minimized.

Copy link

@engmyahya engmyahya commented Jan 28, 2018

great script, I think $web at line 81 should be changed to $spWeb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment