One line Powershell to delete all list items?

Is it possible to have one line powershell to delete all items in a list (no folders)?

I tried this one from http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/de844268-6bb5-4510-9c83-bbca24cf278f,

$list.get_items() | where { $_.column name with spaces -like '3*' } | % { $_.Delete() }.

In my case, I remove the middle part: $list.get_items() | % { $_.Delete() }

I got one item removed with the exception:

An error occurred while enumerating through a collection: Collection was modifi
ed; enumeration operation may not execute..
At line:1 char:1
+  <<<< $list.Get_Items() | % {$_.Delete()}
    + CategoryInfo          : InvalidOperation: (Microsoft.Share...on+SPEnumer
   ator:SPEnumerator) [], RuntimeException
    + FullyQualifiedErrorId : BadEnumeration

Seems I am missing some here - I am running Powershell through SharePoint 2010 Management Shell as Administrator.

March 26th, 2012 3:33pm

this happens because after you delete the first item, the original collection is modified.

You can do a simple while to delete all items:

while($list.Items.Count -gt 0){$list.Items.Delete(0)}
Hope this could help.
  • Marked as answer by Guangming Monday, March 26, 2012 4:57 PM
Free Windows Admin Tool Kit Click here and download it now
March 26th, 2012 4:01pm

that is exactly the solution I ended up. Thanks,

Any idea on what the % does in the line:

$list.get_items() | where { $_.column name with spaces -like '3*' } | % { $_.Delete() }.

March 26th, 2012 4:56pm

% is an alias for Foreach-Object
  • Marked as answer by Guangming Tuesday, March 27, 2012 12:50 PM
Free Windows Admin Tool Kit Click here and download it now
March 26th, 2012 5:00pm

This was the missing piece of the script I'm building.  Thanks.  One question:  Why the 0 in Delete(0)?
April 16th, 2015 11:30pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics