I had written about why you shouldn’t use System.Array and instead should use System.Collections.ArrayList and went over the performance gains regarding this. I had mentioned that each time you add something to the System.Array, that it rebuilt itself while adding the new value. You pretty much took my word on that (thank you!) but I wanted to take that a step further by showing you how this can be viewed using PowerShell along with another quirk with using System.Array that you may not actually be aware of.

So how do we view this happening you ask? Glad you asked that question! We can make use of PowerShell’s own debugging using Set-PSDebug and setting the Trace level to 2 which will allow us to view all of the variable assignments.

Set-PSDebug –Trace 2

Now that we have done this, anything that occurs on the console will have some Debug output stream showing up on the screen as well. So now that this is done, lets create the array and start adding stuff to it.

$Array = @() 1..10 | ForEach { $Array += $_ }

Each time a new item is added to the array, it builds a new array to add the new item into the collection.

The next part of this is something that I wasn’t aware of until I just happened to run the Clear() method while keeping the debug running and then adding some more data to it.

$Array.Count $Array.Clear() 1..2 | ForEach { $Array += $_ }

Instead of adding the new items at the front of the collection, they are instead being added at the end, like the values were never actually cleared at all! And guess, what? They were cleared, but just never removed from the collection.

$Array.count

While you would think that it should only be 2 items, it in fact is 12 items in the collection. The difference is that the first 10 items are actually Null.

For ($i=0;$i -lt $Array.count;$i++) { "Iteration: $i" $Array[$i] } $Array | ForEach { $_ -eq $Null }

While this was new to me, it is actually by design (it pays to read up on the methods that you use ). What is happening is that each item in the collection is set to a specific type of value, in this case Null. More on the Clear() method can be found here.

So with that I hope you have a better understanding of using Set-PSDebug to look a little deeper into using System.Array and what happens when you use the += operator to add items to it as well as looking at what Clear() actually does.