Nigel Boulton's Blog
28Feb/113

Converting a PowerShell Array into a .Net Framework ArrayList

I was writing a PowerShell script earlier today and needed to take some data I had in an array and put it into a .Net Framework ArrayList. It took me some searching online to find out how to do this so I thought I’d blog it here…

ArrayLists are a powerful way of managing data – one of their biggest advantages is that it is easy to manipulate data by adding or removing elements, as shown below. With default PowerShell arrays there is no simple way to remove elements.

To demonstrate how ArrayLists work, try this code:

$ArrayList = New-Object System.Collections.ArrayList
$ArrayList.Add("New Element 1")
$ArrayList.Add("New Element 2")
$ArrayList.Count
$ArrayList.Remove("New Element 2")
$ArrayList.Count

Note that the return value from the Add method is the element number that was added. You can always cast this to void or pipe it to Out-Null if you don’t need it.

You can also specify where to add or remove elements:

$ArrayList.Add(0,"New Element 3") 	# Adds an element at the beginning of the array list
$ArrayList.RemoveAt(0) 				# Removes the first element

Anyway, back to the point... I had an array containing a list of files (which came from Get-ChildItem), and I wanted to create an ArrayList and populate this with that data, because I wanted to be able to remove each file from the list later on in the script. There are two approaches that can be used for this:

From an existing array:

$arrFiles = Get-ChildItem
$colFiles = New-Object System.Collections.ArrayList
$colfiles.AddRange($arrFiles)

Or more simply, populate the ArrayList directly:

$colFiles = New-Object System.Collections.ArrayList(,(Get-ChildItem))

Note the comma within the parameters – the comma is the array construction operator in PowerShell.

Forgive my artistic license in choosing a title for this post – we’re not really converting an array as such, but I thought it would be the most likely thing somebody seeking this information would search for.

Comments (3) Trackbacks (0)
  1. Oh wow, can’t thank you enough for this post.
    I have a powershell script where I have an array about 1 million entries long. Periodically I wanted to shrink the array, and export it to a CSV in case of system crash/restart.
    Trying to copy that array into another, one entry at a time was taking about 10 hours to. Ludicrous.
    Instead, I used the array method above and setup a quick loop to cut through the elements I don’t want:

    for($k= 0; $k -lt $SkipCount; $k++)
    {
    $FileList.RemoveAt(0)
    }

    This runs in a few seconds and makes this script far more manageable. Thanks again.

  2. Nice post. For info you can also do it like this, which is slightly easier to remember syntax.

    $colFiles = [System.Collections.ArrayList](Get-ChildItem)


Cancel reply

No trackbacks yet.