1

I want to find all LookUpFields on SharePoint and copy them to a new SingleLineofText Field but everytime i get the same error > An error occurred while enumerating through a collection: Collection was modified; enumeration operation may not execute.. I found a solution (link) for this problem but I don't real understand how i should modify my script. I hope someone can help me and explain why this is so.

Foreach($site in Get-Site -Limit all)
{ 
    Foreach($web in $site.AllWebs)
     {
       Foreach($list in $web.Lists)
          {
            Foreach($field in $list.Fields)
               {
                if(($field.Type -eq [Microsoft.SharePoint.SPFieldType]::Lookup) -and ($field.Hidden -eq $false))
                    {
                     $fieldname = $field.Title + "_Hidden"
                     $NewHiddenField = $list.Fields[$fieldname]
                     if(!$NewHiddenField)
                        {
                         $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text
                         $list.Fields.Add($fieldname,$spFieldType,$false)
                         $NewHiddenField = $list.Fields[$fieldname]
                         $NewHiddenField.Hidden = $false
                         $NewHiddenField.Update()
                         $list.Update()
                         }
                         else
                         {
                         $spItem = $list.Items
                         $spItem[$NewHiddenField] = $spItem[$field]
                         $spItem.SystemUpdate()
                         }                         
                         Write-Host "Done!!!"
                     }
                }
            }
            $web.Dispose()
        }  
$site.Dispose()}
1

You are changing the collection as you are looping through it. This confuses the iterator and causes it to throw the error.

Suppose you have ten envelopes and need to put stamps on them. Now as you're doing this someone comes along and starts putting new envelopes on the piles, or starts putting different stamps on them as well. Now, you're smart enough to adjust and react accordingly, but code is not smart. It only does what it's programmed to do. Code throws an error because you've corrupted its understanding of the data it's working on.

Instead of creating the field inside the loop, keep track of what changes need to be made (using an array or whatever), and apply them after the loop has completed.

  • Ah, now I got it. Thx – Dimatrix May 12 '17 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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