Powershell – How to Remove Array Elements

Normally, to remove array elements you simply assign the elements you want to keep back to the array’s name. What is really happening is the array is getting copied to a new array with the same name like this:

$array = $array[0..($i – 1)] + $array[($i – 1)..$array.Count-1]

So here is something strange that I noticed today. If you are looping through an array, based on the length of the array, and remove an element; the loop will get stuck in an infinite loop. Here is an example:

[string[]]$array = (1..10)

for ($i = 0; $i -lt $array.Count; $i += 1){

$array = $array[0..($i – 1)] + $array[($i – 1)..$array.Count-1]

}

From what I can see, it looks like the $array.Count in argument list for the for loop only gets calculated once. When an element is removed, it can never break out of the loop because the condition never gets satisfied. If you were to do this in VB it would error out, but not in Powershell, this is a possible bug they will have to fix in a later release.

If you found this useful, subscribe.

Advertisements