PowerShell, adding and removing items from array (list of items)

One of the main problems is understand how to operate on arrays, after that comes tables and at “the end” hashtables.

There are many different solutions, like in “whole PowerShell”

Let’s take a closer look to a list:

$Array = ('Tree', 'Wood', 'Stone', 'Water', 'Air', 'Fire')
$Array | Get-Member

array_1

Now let’s try to add something:

$Array.Add('River')

No, we can’t do it 😦

array_2

So let’s try something else:

$Array.Insert('River')

Nop, we can’t do like this either.

array_3

At the end we comes to this, it is simple and works:

# adding item to the list
$Array = $Array + 'Rain'
$Array += 'Rain'

OK, so corresponding to above example, let’s try to remove something:

# removing item from the list
$Array = $Array - 'Rain'

Nop :-(, so at the moment I feel lite brainwashed 😉

array_4

Let’s try something that’s work, to feel better 🙂

$Newarray = $Array -ne 'Fire'

array_5

Bit longer then oneliner approach, but can be useful:

$remove = 'Fire'
$NewArray = foreach($a in $Array)
{
if($a -ne $remove)
{
$a
}
}

 

Now let’s do the magic:

[System.Collections.ArrayList]$ArrayList = $Array

If you can’t remember words System.Collections.ArrayList (like I do)…
Remember this:

$ArrayListII = {$Array}.Invoke() # don't forget {}

Take a look once again at Get-Member:

$ArrayList | Get-Member

array_6

$ArrayListII | Get-Member

array_7

So what’s going on ?
Let’s revile the secret:

$Array.GetType()
$ArrayList.GetType()
$ArrayListII.GetType()

from an array we create an object:

array_8

Now we can add things in this way:

# adding item
$ArrayList.Add('Wind')

or when we don’t won’t any output:

# adding item
$null = $ArrayList.Add('Sun')

There are more features.

We can add item to specify position on the list:

# adding item
$ArrayList.Insert(5,'LongLongLongWord')
# removing item on specify position on the list
$ArrayList.RemoveAt(7)

# removing item Wind
# pay attention it remove only one (first) item Wind from the list
$ArrayList.Remove('Wind')
# soring
$ArrayList.Reverse()
$ArrayList.Sort()

Trick:
Taking last item from the list:

$Array[-1]

$ArrayList[-1]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s