Disclaimer: There are several ways to do this – if you don’t need the list, just delete the whole list.
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 kinda 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 " Say 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, albeit slowly…
yes, it works too slow. there is better approach – deletion by an xml instruction.
Thanks Bredo, yes I’ve seen this method, and it is preferred from a speed perspective.
You are right in general, however, if there is anything wrong with the XML structure or its content, you get Native Stack error where you can’t understand what went wrong and how to fix it…
Thanks,
it worked for me 🙂
Just FYI to anyone who’s running across this article in the future, I had issues using the SharePoint CSOMs(using O365 SharePoint), with the .delete() method. Powershell claimed the method didn’t exist.
More research led me to this article here: https://msdn.microsoft.com/en-us/library/office/gg701783(v=office.14).aspx
This used .deleteobject() instead of .delete in the same general context as above with C#. .Deleteobject() worked for me.
You can always loop “bottom-up” the list using a for instead of foreach, calling $list.items[$position].delete(). Like this:
$web = Get-SPWeb “http://siteurl”
$list = $web.Lists[“listname”]
#$caml=””
$query=new-object Microsoft.SharePoint.SPQuery
$query.ViewAttributes = “Scope=’Recursive'”
#$query.Query=$caml
$listItems=$list.GetItems($query)
Write-Host $listItems.Count
$listItemsTotal = $listItems.Count
# $listItems | % { $list.GetItemById($_.Id).Delete() }
for ($x=$listItemsTotal-1;$x -ge 0; $x–)
{
Write-Host(“DELETED: ” + $listItems[$x].Id)
$listItems[$x].Delete()
}
$web.Dispose()
$site.Dispose()