PowerShell - Enumerating through a collection and change the collection

The SPListCollection tends to modify the collection when updating its properties (fields, event receivers, etc.). You can use a for-loop instead:

for ($i = 0; $i -lt $webLists.Count; $i++)
{
  $list = $web.Lists[$i];
  # ...
}

You can try copying the collection you're currently iterating on to another collection (an array or a list) and then iterate on that new collection.

Something like this:

$collection = @(1, 2, 3, 4)
$copy = @($collection)
$collection[0] = 10
$collection -join " "
$copy -join " "

The code above gives the following output:

10 2 3 4
1 2 3 4

Note that the $copy variable refers to a different collection.


I know this is a pretty old thread. This is for anybody ending up to this page looking for an answer.

The idea is, like other answers suggest, to copy the collection (using the clone() method) to another and iterate "another" and modify the original variable inside the loop without having to use for in place of foreach:

A collection of type ArrayList:

[System.Collections.ArrayList]$collection1 = "Foo","bar","baz"
$($collection1.Clone()) | foreach {
$collection1.Remove("bar")
}

Output:

PS H:\> $collection1
Foo
baz

A collection of type Hashtable:

[System.Collections.Hashtable]$collection2 = @{
        "Forum" = "Stackoverflow"
        "Topic" = "PowerShell"
        }

$($collection2.Clone())| foreach {
$collection2.Remove("Forum")
}

Output: PS H:> $collection2

Name                           Value                                                              
----                           -----                                                              
Topic                          PowerShell                                                         

And, a basic array:

[System.Array]$collection3 = 1, 2, 3, 4
$($collection3.Clone()) | foreach {
$collection3[$collection3.IndexOf($_)] = 10
}

Output:

PS H:\> $collection3
10
10
10
10

As long as your collection is not of fixed size.