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?

up vote 2 down vote accepted

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()
}

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();
    }
}

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();

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.