Manipulating Arrays Effectively

by Dec 4, 2008

While you can add and remove array elements with PowerShell arrays, this is an expensive operation and not recommended with large numbers of elements. Instead, use a .NET ArrayList if you need to dynamically expand and shrink an array at runtime:

$array = New-Object System.Collections.ArrayList
$array.Count
$array.Add("a new element")
$array.Add((Get-Date))
$array.Add(100)
$array.Count

Note that every time you add a new element to the array using Add(), you will get back the index position at which the element was inserted. If you don't need that information, discard it:

[void]$array.Add(200)

ArrayList arrays allow you to insert elements anywhere in the array. The next line inserts a new element at the beginning:

$array.Insert(0, 'new element at the beginning!')

You can also remove elements by simply specifying the content. The next line removes the first element with a value of 200:

$array.Remove(200)

With RemoveAt(), you remove array elements at a specific position. The next line removes the first element:

$array.RemoveAt(0)

Use square brackets to access individual elements:

$array[0]