Adding and Removing Items from a PowerShell Array

Adding and removing Items from a PowerShell array is a topic which can lead to some confusion, so here are a few tips for you.

Create an array and we will note the type System.Array:

$Fruits = "Apple","Pear","Banana","Orange"


However, if we try to Add or Remove items to the array we get errors that the “Collection was of a fixed size”

$Fruits.Add("Kiwi") $Fruits.Remove("Apple") $Fruits.IsFixedSize

We can see that the array we originally created is of a fixed size. The MSDN page for the ISFixedSize Property helps to explain this. Note it supports the modification of existing elements, but not the addition or removal of others.

One way to deal with this is to use a System.Collections.ArrayList instead

\[System.Collections.ArrayList\]$ArrayList = $Fruits $ArrayList.GetType()

Now if we try the previous add and remove methods we are successful:

$ArrayList.Add("Kiwi") $ArrayList $ArrayList.Remove("Apple") $ArrayList

Alternatively, if we had stuck with the original Array object we could do the following to ‘add’ an item to it. (Actually it creates a new array with an additional item)

$New = $Fruits += "Kiwi" $New $New.GetType()

However, we can’t remove items in this way:

$New2 = $Fruits -= "Apple"

We could instead do this:

$New3 = $Fruits -ne "Apple" $New3


Update: Thanks to Rob Campbell for pointing out another way to do this.

Taking your initial array you can convert it to a System.Collections.ObjectModel.Collection`1 like this, which may be easier to remember than using the full type name of either a collection or array list:

$Collection = {$Fruits}.Invoke() $Collection $Collection.GetType()

Now we can add and remove items using the Add and Remove methods:

$Collection.Add("Melon") $Collection $Collection.Remove("Apple") $Collection