“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.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”,
$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