I've found some interesting behaviour in PowerShell Arrays, namely, if I declare an array as:
$array = @()
And then try to add items to it using the $array.Add("item")
method, I receive the following error:
Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."
However, if I append items using $array += "item"
, the item is accepted without a problem and the "fixed size" restriction doesn't seem to apply.
Why is this?
When using the
$array.Add()
-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.$array += $element
creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the$array
-variableSource: about_Arrays
+=
is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:If that's not possible, consider using a more efficient collection like
List
orArrayList
(see the other answer).If you want a dynamically sized array, then you should make a list. Not only will you get the
.Add()
functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.And it's so easy to use.
Instead of your array declaration, try this:
Adding items is simple.
And if you really want an array when you're done, there's a function for that too.
The most common idiom for creating an array without using the inefficient
+=
is something like this, from the output of a loop: