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


Now let’s try to add something:


No, we can’t do it 😦


So let’s try something else:


Nop, we can’t do like this either.


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 😉


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

$Newarray = $Array -ne 'Fire'


Bit longer then oneliner approach, but can be useful:

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


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


$ArrayListII | Get-Member


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


from an array we create an object:


Now we can add things in this way:

# adding item

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
# removing item on specify position on the list

# removing item Wind
# pay attention it remove only one (first) item Wind from the list
# soring

Taking last item from the list:



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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s