How to Create an Empty Array in PowerShell (With Example)


You can use the following syntax to create an empty array in PowerShell:

$my_array = @()

This particular example creates an array named $my_array that has no elements.

Note that we use the @ symbol to declare an array and we don’t specify any elements in the parentheses to indicate that the array should be empty.

Once we’ve created the array, we can use the following syntax to add elements to it:

$my_array += 1

This particular example adds the value 1 to the array.

We can also use the following syntax to add an array with several elements to the empty array:

$my_array = $my_array + ,(2,3,4)

This particular example adds an array with the values 2, 3 and 4 to the existing empty array.

Note that the comma specifies that the new elements being added all belong to the same array within the empty array.

The following example shows how to use this syntax in practice.

Example: How to Create an Empty Array in PowerShell

We can use the following syntax in PowerShell to create an empty array named $my_array and then use the length property to verify that the array is empty:

$my_array = @()

$my_array.length

The following screenshot shows how to use this syntax in practice:

PowerShell create empty array

Notice that the output returns 0, which indicates that we’ve successfully created an empty array with no elements.

We can use the following syntax to then add the value 1 to the array:

$my_array += 1

The following screenshot shows how to use this syntax in practice:

PowerShell create empty array and add item to it

When we view the array again we can see that it contains one element with the value 1.

We can also use the following syntax to add an array within the array that contains the values 2, 3 and 4:

$my_array = $my_array + ,(2,3,4)

The following screenshot shows how to use this syntax in practice:

PowerShell create empty array of arrays

Notice that a new array has been added with the values 2, 3 and 4 to the original array.

Also notice that the length property of the array returns 2 since we added these new elements in a single array.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if Array is Empty
PowerShell: How to Divide an Array into Smaller Chunks
PowerShell: How to Add Item to Array Only if it Doesn’t Exist

Leave a Reply