Delete All Items from List or Library using PowerShell

At times, we may have to delete all items from SharePoint list or library. We can get it done by going to "Manage Content and Structure" option as in my another article How to Remove All responses from SharePoint Survey

There may be situations, where we've to delete all items from SharePoint list programmatically. Here are the code snippets to achieve the same.

Delete All Items from SharePoint List or Library using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebURL = ""

#Get web List and List Items
$Web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]
$ListItems = $List.items
Write-host "Total Items in the List:"$List.ItemCount

#Iterate through each Item in the list
foreach ($Item in $ListItems)
    Write-host "Deleted Item: $($" -foregroundcolor Red
Traditional Way of deleting Items from end to avoid: "Collection was modified" Error
for ($i=$listItems.Count-1;$i -ge 0; $i-–)
Write-Host("Deleted: " + $listItems[$i].name)

One-Line PowerShell script to remove all items from SharePoint List:
(Get-SPWeb http://your-sharepoint-site).Lists["ListName"].Items | % { $_.ParentList.GetItemById($_.ID).Delete() }

Filter and Delete List Items:
We can filter the list items using CAML and perform the same delete operation. Here it goes:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

$url = ""
$web = Get-SPWeb $url
#Get the List
$list = $web.Lists["Tasks"]

#CAML Filter Query
$CAMLQuery="<Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>Completed</Value></Eq></Where>"

$SPQuery=New-Object Microsoft.SharePoint.SPQuery
$SPQuery.ViewAttributes = "Scope='Recursive'"  #Get all items from Folders also!
$SPQuery.RowLimit  = 10000; 

#Get the List items based on Filter 

#Delete the items from list
$result | % { $list.GetItemById($_.Id).Delete()  }

Delete All Items from SharePoint list Programmatically using C# Object Model:
Same code can be re-written in C# to delete list items programmatically.
           using (SPSite oSPsite = new SPSite("http://sharepoint"))
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                        oSPWeb.AllowUnsafeUpdates = true;

                        // Get the List
                        SPList oSPList = oSPWeb.Lists["Tasks"];

                        for (int i= oSPList.ItemCount-1; i >=0; i--)

                        oSPWeb.AllowUnsafeUpdates = false;

Bulk Delete using ProcessBatchData:
   using (SPSite oSPsite = new SPSite("http://sharepoint"))
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                        // Get the List
                        SPList oSPList = oSPWeb.Lists["Tasks"];

                        StringBuilder batchString = new StringBuilder();
                        batchString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

                        foreach (SPListItem item in oSPList.Items)
                            batchString.Append("<SetList Scope=\"Request\">" + Convert.ToString(item.ParentList.ID) + "</SetList>");
                            batchString.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
                            batchString.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");


PowerShell script to delete in Bulk from SharePoint list:

Function global:Get-SPWeb($url)
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
    return $web

$WebURL =""
$ListName ="DSF_Transactions"
$BatchSize = 1000  #Lets delete 1000 items at a time

#Get the web object
$web = Get-SPWeb $WebURL
#Get the List
$list = $web.Lists[$ListName]

while ($list.ItemCount -gt 0)

    Write-host "Total Number of Items:"$list.itemcount
    $StringBuilder = New-Object System.Text.StringBuilder
    $StringBuilder.Append("<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>") > $null

    foreach($item in $List.Items)
    $StringBuilder.Append("<Method><SetList Scope=`"Request`">$($list.ID)</SetList><SetVar Name=`"ID`">$($item.ID)</SetVar><SetVar Name=`"Cmd`">Delete</SetVar></Method>") > $null
        if($BatchCount -ge $BatchSize) { break } #Break from this foreach loop

    $stringbuilder.Append("</ows:Batch>") > $null

    $web.ProcessBatchData($StringBuilder.ToString()) > $null
Don't forget to Add, when you are deleting from a library:
<SetVar Name=`"owsfileref`">$($item.File.ServerRelativeUrl)</SetVar>
Deleting SharePoint list items using ProcessBatchData method sends items to Recycle bin!

Delete Vs Recycle: Will the Deleted Items goes to Recycle bin?
No! Delete method doesn't send files to Recycle bin. But the Recycle Method does! So, call the Recycle method , if you want the deleted items to be sent to Recycle bin.
using (SPWeb web = siteColl.AllWebs["Sales"])
  SPList list = web.Lists["Tasks"];
  SPListItem item = list.Items[GUID];
You can also: Save list as template (without content), Delete the list and Re-create from the list template! - Provided if there is no workflow/event receiver associated with the list.
Delete All Items from List or Library using PowerShell Delete All Items from List or Library using PowerShell Reviewed by Salaudeen Rajack on November 12, 2012 Rating: 5

1 comment:

Please Login and comment to get your questions answered!

Powered by Blogger.