1

I am trying to delete items in my sharepoint list something like this:

   foreach ($li in $listitems) 
    {
                if ($li.id -eq 100 )
                    {
                      $li.Delete();
                    }
                }
     }

But this error comes up:

Collection was modified; enumeration operation may not execute.

How can I delete listitems in a foreach loop?

bier hier
  • 172
  • 2
  • 8

3 Answers3

2

As stated in error message, delete item operation inside listItemCollection using for each loop would modify the source collection on which the for each loop is iterating.

Hence, try to create a separate collection of items which you want to delete and then perform delete operation on it.

$itemsToDelete = @()

foreach($li in $listitems) {
    if($li.id -eq 100)
    {
        $itemsToDelete += $li
    }
}

foreach($item in $itemsToDelete) {
    $item.Delete()
}
Yayati
  • 1,728
  • 4
  • 16
  • 35
1

You have to

  • refer to items by their index in the collection (i.e. not foreach)
  • loop backwards through the collection

Something like this (this is going to be a little more C#-ish than Powershell, the exact Powershell syntax is not coming to me at the moment, but you will get the idea):

var length = listitems.count - 1;
for (var idx = length; idx >= 0; idx--) {
    if (listitems[idx] -eq 100) {
        listitems[idx].Delete();
    }
}
Dylan Cristy
  • 12,712
  • 3
  • 31
  • 71
0

Try this and see if it works:

foreach ($li in $listitems) 
    {
                if ($li.id -eq 100 )
                    {
                      $listitems.Delete($li);
                    }
                }
     }

You could also try replacing above delete line with (Still wrapped with the loop obviously):

$listitems[$li].Delete();
Shane Gib.
  • 408
  • 1
  • 5
  • 14
  • Check out this article as well for other ways to delete list items using powershell:

    https://sharepoint.stackexchange.com/questions/38115/how-to-delete-all-items-in-a-list-using-powershell

    – Shane Gib. Apr 16 '18 at 13:42