Different options to delete all items in a SharePoint list with PowerShell

Disclaimer :

There are several ways to do this – if you don’t need the list, just delete the whole list.

Option 1 :

If you have only small number of rows in a list go with this option.
If you need the structure of the list and just need to delete the items in the list, this script will do it, but there are faster methods out there so if you have 1000′s of items, know that this approach is kind of slow.
You might think (As I did) that once you had the list you could do something clever like:

$list.items.delete() #this fails


write-host "This will delete data, type YES to continue"
$retval = read-host
if ($retval -ne "YES")
{
write-host "exiting - you did not type yes" -foregroundcolor green
exit
}
write-host "continuing"

$web = get-spweb https://url to your web
$list = $web.lists | where {$_.title -eq “Name_of_your_list”}
Write-host “List $($list.title) has $($list.items.count) entries”
$items = $list.items
foreach ($item in $items)
{
Write-host ” Goodbye to $($item.id)” -foregroundcolor red
$list.getitembyid($Item.id).Delete()
}

You might also wonder why we getitembyID. You might wonder why we don’t just put $item.delete() inside the foreach loop – that fails too, so we get around that with the last line which seems to work.

Option 2:

Compared to the simple item by item delete with item.Delete() its 30 times faster; It works for SharePoint 2010 and should for 2013 (not tested).

param($weburl,$listname)
if ($weburl -eq $null -or $listname -eq $null)
{
write-host -foregroundcolor red "-weburl or -listname are null."
return
}

Add-PSSnapin Microsoft.SharePoint.Powershell -EA 0
$web = get-spweb $weburl
$list = $web.lists[$listname]

$stringbuilder = new-object System.Text.StringBuilder

try
{
$stringbuilder.Append(“”) > $null

$i=0

$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewFieldsOnly = $true

$items = $list.GetItems($spQuery);
$count = $items.Count

while ($i -le ($count-1))
{
write-host $i
$item = $items[$i]

$stringbuilder.AppendFormat(“”, $i) > $null
$stringbuilder.AppendFormat(“{0}”, $list.ID) > $null
$stringbuilder.AppendFormat(“{0}”, $item.Id) > $null
$stringbuilder.Append(“Delete”) > $null
$stringbuilder.Append(“”) > $null

$i++
}
$stringbuilder.Append(“”) > $null

$web.ProcessBatchData($stringbuilder.ToString()) > $null
}
catch
{
Write-Host -ForegroundColor Red $_.Exception.ToString()
}

write-host -ForegroundColor Green “done.”

Usage

Save above code as “DeleteItems.ps1”.
Create a batch file with below lines
@echo off
set “workingDir = %cd%”
powershell -Command “& {%cd%\DeleteItems.ps1 -weburl:your web url -listname:your list name -action:SD}” -NoExit
pause

Disclaimer

There is no way back – if you start the script there is no “ARE YOU SURE?” – all data is gone in a very short time.

Leave a comment