Sometimes when I’m working on something related to SharePoint, I come across scenarios where I’m constantly building up test data in Lists. Frequently when doing this, I have a need to almost constantly delete and recreate list items.
Rather than using the UI or writing nice PowerShell one-liners (which for the record I love doing), I decided to throw together a little script for this.
This script takes two mandatory parameters, one for URL and one for List Name. Assuming you give it the correct values, it will quickly use Object Model code to call the Delete() method against every item in the list (or library).
Here is the script, hope it works for you! Note: I did not add any kind of confirmation, so if you run this – it WILL literally delete all items, it won’t first make sure you’re serious about it – so make sure you know what you’re doing! 🙂
RD
<# .Synopsis Use this PowerShell Script to delete all list items, very quickly! .Description This advanced script uses SharePoint Cmdlets and the SP Object Model to bulk delete SharePoint list items from a specified SPList. .Example C:\PS>.\Delete-SPListItems.ps1 -Url http://intranet -ListName "Test List" This example deletes list items from a list called Test List in the http://intranet web. .Notes Name: Delete-SPListItems Author: Ryan Dennis Last Edit: 8/2/2012 Keywords: Delete List Items .Link http://www.sharepointryan.com http://twitter.com/SharePointRyan .Inputs None .Outputs None #Requires -Version 2.0 #> [CmdletBinding()] Param( [Parameter(Mandatory=$true)][System.String]$Url, [Parameter(Mandatory=$true)][System.String]$ListName ) $Web = Get-SPWeb $Url $List = $Web.lists[$ListName] if($List -eq $null){ Write-Error "The List cannot be found";return } Write-Warning "Deleting all list items from $($ListName)" $Items = $List.GetItems() $Items | ForEach-Object{ $List.GetItemById($_.Id).Delete() } $List.Update() $Web.Dispose()
If you have a very large number of list items to delete you can also do a bulk delete such as in the below link. It calls the SPWeb.ProcessBatchData method with a CAML query (can be built dynamically) to specify the list.
http://www.sharepointdev.net/sharepoint–development-programming/bulk-deletion-of-sharepoint-list-items-42533.shtml
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.processbatchdata.aspx
Awesome, good to know, thanks Brian!
Hi so useful … I am using it a function prior to uploading SPItems form a .CSV file …
Awesome, glad it was helpful!