. Advertisement .
. Advertisement .
An array in PowerShell and other languages is always a fixed size. This combination of items is represented by a variable. For this reason, adding or removing any item from this one can lead to unwanted confusion, especially for beginners.
This post focuses on giving some useful tips to add items to an array in the PowerShell.
How To Add Items To An Array In The PowerShell
Before learning to add an item to a PowerShell array, let’s create an array first. For example, you have the following array
$Names as follows:
$Names = "Paul", "John", "Peter"
What if you use the
Array.Add() function to add a new item? As its fixed length cannot be extended, there would be an error when you execute the code:
$names = "Paul","John","Peter" $names.Add("Simon")
There are two approaches to deal with this error. You can either create a new array and remove the existing one or use the
Yet, the former method can mess up the program and make it hard to track the original code. We highly recommend you use the latter one. This PowerShell operator can be used to concatenate various strings together or add new items to several lists at once.
All you have to do is to type out the variable with the
+ <Another Item Name> behind.
$names = "Paul","John","Peter" $names += "Simon"
The result will not remove the existing contents. Instead, you will receive the original array and a new one with the copied contents and new added elements.
While this approach works well, there is still a more common one to accomplish the task. The += operator will also work out the same result.
It is a PowerShell shortcut to add new items to the existing array. It prevents you from typing out the long array name for the second time. That’s why using the plus and equals signs to add new items is more widely used than using the full syntax.
If your array is too long and using these two operators cannot handle the complicated task, it would be better to use ArrayList instead of a common array.
Unlike an array, the ArrayList is not fixed in length. You can easily change and store the data type. To turn an array to an ArrayList, let’s execute the following command:
$Name = New-Object System.Collections.ArrayList $Name.IsFixedSize
In this case, use the
ArrayList.Add() method to add new items:
$Name.Add("Paul") $Name.Add("John") $Name.Add("Peter") $Name
Paul John Peter
Working with PowerShell arrays is straightforward as long as you get the hang of it. For beginners, the biggest problem is undoubtedly to figure out where and when you have an array.
The tutorial has introduced you to various methods to add items to an array in PowerShell for optimal use and efficient program operation.