Wednesday 2 July 2014

Collection was modified; enumeration operation may not execute Powershell


 “Collection was modified; enumeration operation may not execute,

 Occurs in  foreach loops while you are enumerating through the loop and trying to modify items.

Which modifys the first item in the loop and throws this error without modifying the rest of the items.


Generally it occurs if you try and modify a collection’s references while using foreach to enumerate through it.
For example:

I  am trying to remove all the Supported UI Languages ,by retaining only site created in default site Locale and english locale.


    if($web.IsMultilingual -eq $true  )

      {

        foreach($cul in $web.SupportedUICultures)
       {
         if($cul.LCID -ne  $webCul.LCID -and $cul.LCID -ne "1033")
         {    

           $web.RemoveSupportedUICulture($cul)
          
        
          }
       $web.Update()
       }
    }


for the first time it will go through the loop foreach will remove supported culture for frist time, when it comes to loop for the second iteration then it will throw you the exception  Collection was modified; enumeration operation may not execute,

Solution to Above problem is to Store to values to be modified in a Arraylist and try to modify which will fix the problem, Here i am storing  Arraylist called enumcul and inserting values into it and modifying it...

  
  $enumcul=New-Object Collections.ArrayList
    $i=0
    if($web.IsMultilingual -eq $true  )
      {

        foreach($cul in $web.SupportedUICultures)
       {
         if($cul.LCID -ne  $webCul.LCID -and $cul.LCID -ne "1033")
         {

          $enumcul.Insert($i, $cul)
          $i=$i+1
          }
     
       }

      
     foreach$k in $enumcul)
     {
     
        $web.RemoveSupportedUICulture($k)
        $web.Update()
     }

No comments:

Post a Comment