Welcome PowerShell User! This recipe is just one of the hundreds of useful resources contained in the PowerShell Cookbook.

If you own the book already, login here to get free, online, searchable access to the entire book's content.

If not, the Windows PowerShell Cookbook is available at Amazon, or any of your other favourite book retailers. If you want to see what the PowerShell Cookbook has to offer, enjoy this free 90 page e-book sample: "The Windows PowerShell Interactive Shell".

7.7 Combine Two Arrays

Problem

You have two arrays and want to combine them into one.

Solution

To combine PowerShell arrays, use the addition operator (+):

PS > $firstArray = "Element 1","Element 2","Element 3","Element 4"
PS > $secondArray = 1,2,3,4
PS >
PS > $result = $firstArray + $secondArray
PS > $result
Element 1
Element 2
Element 3
Element 4
1
2
3
4

Discussion

One common reason to combine two arrays is when you want to add data to the end of one of the arrays. For example:

PS > $array = 1,2
PS > $array = $array + 3,4
PS > $array
1
2
3
4

You can write this more clearly as:

PS > $array = 1,2
PS > $array += 3,4
PS > $array
1
2
3
4

When this is written in the second form, however, you might think that PowerShell simply adds the items to the end of the array while keeping the array itself intact. This is not true, since arrays in PowerShell (like most other languages) stay the same length once you create them. To combine two arrays, PowerShell creates a new array large enough to hold the contents of both arrays and then copies both arrays into the destination array.

If your plan is to add and remove data from an array frequently, the System.Collections.ArrayList class provides a more dynamic alternative. For more information about using the ArrayList class, see Recipe 7.12.

See Also

Recipe 7.12, “Use the ArrayList Class for Advanced Array Tasks”