Here is a simple script in C #:
var intList = new List<int>(); intList.Add(4); intList.Add(7); intList.Add(2); intList.Add(9); intList.Add(6); foreach (var num in intList) { if (num == 9) { intList.Remove(num); Console.WriteLine("Removed item: " + num); } Console.WriteLine("Number is: " + num); }
This throws an InvalidOperationException
, because I change the collection when it is enumerated.
Now consider the similar PowerShell code:
$intList = 4, 7, 2, 9, 6 foreach ($num in $intList) { if ($num -eq 9) { $intList = @($intList | Where-Object {$_ -ne $num}) Write-Host "Removed item: " $num } Write-Host "Number is: " $num } Write-Host $intList
This script actually removes number 9 from the list! There were no exceptions.
Now I know that the C # example uses a List object, while the PowerShell example uses an array, but how does PowerShell list the collection that will be modified during the loop?
source share