Adding and Removing Items from a PowerShell Array

In this article i will show you how to add and remove items from a powershell array. 

Create an Array in Powershell using System.Array

If we create an array and run the command to get the type of our array you will find the base type as System.Array. Now the interesting part here is if you try to add a new item to the array you will get an error.

Let’s try to add/remove items from an array which we have created.

I guess the output say’s a lot. We have originally created a fixed size of array. 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.

Solution 1 – Use  $array += $element

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable. Below is an example on how to use it

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. 

Solution 2 Dynamic Sized array using List

If your requirement is to use Dynamic sized array then you should consider using List. This is the most efficient way of creating an array compared to the other solution

If you want to remove an item from an array you could use $items.Remove(“Node.JS”)

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.