4/14/2015

PowerShell: Collection was modified; enumeration operation may not execute

 

While the following example is for PowerShell, the same applies to C# code.

Collections that are being modified do not like to be processed with FOR EACH.
"Collection was modified; enumeration operation may not execute"

For example:

$web = Get-SPWeb someurl...

ForEach($list in $w.Lists)
{
  if (!$list.Hidden)
  {
    # do something to change the list
    # like add a new view...

    $list.Views.Add(.......)
    # error! 
    # "Collection was modified; enumeration operation may not execute..."
  }
 }
$web.Dispose()

 

The Fix

Change the FOR EACH to a FOR.

change:

  foreach($l in $web.Lists)
     {

to:

   for ($i=0; $i -lt $web.lists.count; $i++)
     {
        $l = $w.lists[$i]

 

And if you are deleting items in the collection…

Walk the collection in reverse order!

   for ($i=$web.lists.count-1; $i –gt 0; $i--)
     {
        $l = $web.lists[$i]

.

1 comment:

Anonymous said...

And if you are deleting items in the collection…
Walk the collection in reverse order!

for ($i=$web.lists.count-1; $i –gt 0; $i--)
{
$l = $web.lists[$i]

is wrong...The -gt should be -ge. This approach was the solution to my problem though. Thanks.

Note to spammers!

Spammers, don't waste your time... all posts are moderated. If your comment includes unrelated links, is advertising, or just pure spam, it will never be seen.