How to Combine Two Arrays in PowerShell (With Example)


Often you may want combine the elements of two arrays into one array in PowerShell.

The easiest way to do so is by using a $ symbol followed by parentheses with the name of each array inside the parenthesis, separated by a semicolon:

$final_array = $($my_array1; $my_array2)

This particular example will combine the elements from the arrays named my_array1 and my_array2 into one array named final_array.

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

Example: How to Combine Arrays in PowerShell

Suppose that we have two arrays named my_array1 and my_array2 and we would like to combine them into one single array.

We can use the following syntax to do so:

$my_array1 = @(2, 5, 5, 6, 7, 9)
$my_array2 = @(14, 20, 15, 10, 11, 17)

$final_array = $($my_array1; $my_array2)

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

PowerShell combine arrays

We can see that the new array named final_array contains all of the elements from my_array1 and my_array2.

We can verify that the new array is indeed one array with all elements from the two arrays instead of an array of two arrays by using Count to count the number of elements in the new array:

$final_array.Count

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

We can see that the new array named final_array has  a count of 12 total elements, which tells us that we have successfully combined the two arrays into one.

Note that it’s important that we use a semicolon inside the parentheses when combining the two arrays or else the final array will simply be an array of two arrays.

For example, suppose that we used a comma to combine the two arrays instead:

$final_array = $($my_array1, $my_array2)

$final_array.Count 

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

We can see that the count of final_array is 2, which tells us that this combined array is actually just one array of two arrays, which is not what we want.

Related Tutorials

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

PowerShell: How to Add Column to CSV
PowerShell: How to Use Export-Csv with No Headers
PowerShell: How to Use Export-Csv and Specify Column Order

Leave a Reply