How To Create Empty Array And Add Items In PowerShell?

Recently, I got a requirement for creating an empty array and add items in PowerShell. I will explain step by step, how to create empty array and add items in PowerShell.

To create an empty array in PowerShell, you can initialize it with $array = @(). To add items to the array, use the += operator, for example, $array += ‘newItem’. This will append ‘newItem’ to the end of the array. Keep in mind that using += to add items to an array in PowerShell is not the most efficient method for large data sets due to the way arrays are resized.

Create Empty Array And Add Items In PowerShell

Now, let us see, how to create an empty array in PowerShell and then will add item into the PowerShell empty array.

To create an empty array in PowerShell, you can use the following syntax:

$myArray = @()

This command initializes $myArray as an empty array with no elements in it. The @() symbol is the PowerShell array operator, indicating that you’re creating an array.

Now, let us see how to add item to the above empty array in PowerShell.

Once you have an empty array, you may want to add items to it. There are several methods to add an item to a PowerShell empty array.

Method 1: Using += Operator

The += operator allows you to add elements to the end of an array in PowerShell:

$myArray = @()
$myArray += 'Item1'
$myArray += 'Item2'
$myArray += 'Item3'

After executing these commands, $myArray will contain three elements: ‘Item1’, ‘Item2’, and ‘Item3’.

I have executed the PowerShell script using VS code and you can see the output in the below screenshot.

Create Empty Array And Add Items In PowerShell

Method 2: Using Add() Method with ArrayList

Here is another approach to add items to an empty array in PowerShell. You can use PowerShell arraylist, which provides a built-in Add() method. This method can be more efficient, especially when working with large arrays:

$arrayList = New-Object System.Collections.ArrayList
$arrayList.Add('Item1') > $null
$arrayList.Add('Item2') > $null
$arrayList.Add('Item3') > $null

The > $null part is used to suppress the output that the Add() method normally returns (the index of the newly added item).

Method 3: Using Array Concatenation

This is also another approach to add elements to PowerShell array. You can also add multiple elements at once by concatenating another array in PowerShell.

$myArray = @()
$myArray += @('Item1', 'Item2', 'Item3')

This command will add all three items to $myArray in one go to the PowerShell empty array.

Check out the screenshot for the output after I executed the PwoerShell script.

powershell add item to empty array

Conclusion

I hope you got a complete idea of how to create an empty array in PowerShell and add items to the PowerShell array using the below three methods with examples:

  • Using += Operator
  • Using Add() Method with ArrayList
  • Using Array Concatenation

You may also like: