Merge Arrays in PowerShell

PowerShell merge arrays

Using + Operator

Use + operator to merge arrays in PowerShell.

We used the sub-expression operator represented by @() to create two separate arrays named $array1 and $array2 (you can also create arrays without using the sub-expression operator). Note that both arrays contained string-type values.

Next, we used the + operator to join $array1 and $array2 and assigned the merged array to the $merged_array variable, which was further used with the echo command to display on the PowerShell console.

The order of the arrays while using the concatenation operator (+) is more important. In the above example, the elements of $array1 were followed by $array2 elements because we concatenated them as $array1 + $array2.

To have the items of $array2 first, concatenate both arrays as $array2 + $array1. See the following example.

Let’s take another use case where both arrays should have at least one duplicate element but the merged array must contain unique values. Here, we are required to remove identical items by case-sensitive check. See the below example for a clear understanding.

Again, we created two arrays, $array1 and $array2, containing string elements. We used the + operator to concatenate them and stored the merged array in the $merged_array variable. Now, the $merged_array had duplicate items ("are" and "you") that we wanted to remove by case-sensitive check.

To do that, we piped the $merged_array to the Select-Object cmdlet, which selected the unique items using -Unique parameter. This parameter specified that if the subset of the input has identical values or properties, only one member of the subset should be chosen.

As this parameter is case-sensitive, the strings differ in character-casing and would be considered a unique value; for instance, Hi and hi differ. Remember, the -Unique parameter will select items after applying other filtering parameters (if you use them). And the first instance of the duplicate value would be included in the results; see the above output.

What should you do if you want to merge two arrays and remove identical items from the merged array by case-insensitive check? For this particular use case, we will get the advantage of the Sort-Object cmdlet with -Unique parameter as demonstrated below.

This code fence is similar to the last one, but we used the Sort-Object with the -Unique parameter to remove duplicates from $merged_array by case-insensitive check.

The Sort-Object cmdlet is used to sort objects in descending or ascending order; by default, it sorts in ascending order; you must mention the -Descending parameter to sort in descending order.

We used the default behaviour of the Sort-Object cmdlet, as we had string items in both arrays so that they would be sorted alphabetically from A to Z characters.

The -Unique parameter indicated the Sort-Object cmdlet to remove duplicate items and return the unique members of the given input ($merged_array). It included the first instance of the duplicate value in the sorted output.

Here, the -Unique parameter is case-insensitive, which means strings that differ in character-case will be considered the same; for example, "World" and "world" are the same strings.

Using += Operator

Use the += operator to merge arrays in PowerShell.

This example resembles the one where we used the + operator to concatenate/merge the arrays, but we used the += operator this time. The += operator is preferred where we do not want to create a new variable to hold the merged array but want to update the current array, as we modified the $array1 by merging the elements of $array2 into it.

Again, the order of specifying the variable names matters a lot. For example, the output of $array1 += $array2 and $array2 += $array1 would differ, so be careful while writing the variable names.

Here, we can use the Select-Object and Sort-Object cmdlets with the -Unique parameter to remove the identical values from the merged array by case-sensitive and case-insensitive checks. We have learned these cmdlets and parameters in the previous section; you can refer to that.

-Unique parameter is case-sensitive while using it with the Select-Object cmdlet. On the other hand, it is case-insensitive while using it with the Sort-Object cmdlet.

Using a Comma

Use a comma (,) to merge two arrays in PowerShell. The merged array must be an array of arrays.

Alternatively, merge the arrays as follows if you want to have $array2 followed by the $array1 in the merged array.

As the $merged_array is an array of arrays, we can not use Select-Object or Sort-Object to remove identical elements, as both cmdlets work on individual objects. To use these commands, we need to flatten the array first. How? Let’s learn it in the following example.

Using AddRange() Method

Use the AddRange() method to merge two arrays in PowerShell, but the merged array must be an ArrayList.

After creating two arrays ($array1 and $array2), we used the New-Object cmdlet to instantiate the ArrayList class and assign its reference to the $merged_array variable.

Next, we chained the AddRange() method with the $merged_array variable to add elements of the specified collection (which was an array in our case) to the end of an array list. Finally, we printed the $merged_array on the PowerShell console.

We can also use Select-Object/Sort-Object cmdlets with the -Unique parameter (already learned in the first section) to eliminate duplicate items from the merged array list.

Until now, we have gone through various ways to merge two arrays where the elements of the second array follow the elements of the first array. What if we are supposed to merge two arrays by fetching the items from every array one by one? How can it be accomplished? Let’s see it in the following section.

Using for Loop

To merge two arrays by getting the elements from each array one by one in PowerShell:

  • Create two arrays containing string values.
  • Create an empty array to hold merged content.
  • Use the Max() method to grab the maximum size from both arrays created in the first step and assign it to a variable.
  • Use the for to loop over the arrays created in the first step.
  • In each iteration:
    • Grab the current element and append it to the array created in the second step.
  • Use echo to print the merged array.

In the above example, we created three arrays. The first array ($firstNames) contained the first names, and the second array ($lastNames) had the last names, while the third array ($merged_array) was empty. We used the @() operator to create all these arrays; you can also create without using this operator.

Next, we used the Max() function to get the maximum value from the given length of the $firstNames and $lastNames arrays. Note that we got the length of each array using their Length property.

We stored the maximum value, returned by the Max() function, in the $MaxArraySize variable, which we further used within the for loop to iterate $MaxArraySize times over the $firstNames and $lastNames arrays.

We retrieved the current element in each iteration and appended it to the $merged_array using the += operator. Finally, we used the echo command to print the $merged_array on the console.

We can modify the above code to get the fetched elements next to each other with a header; see the following code fence.

The above code is similar to the last one, with a few modifications. Here, inside the for loop, we used the Write-Verbose cmdlet to write a verbose message denoting the current values of the $firstNames and $lastNames arrays.

We used [PSCustomObject]@{} notation to create an object having two properties: FirstNames and LastNames, which were set to the current values of $firstNames and $lastNamesarrays. Then, the created object in each iteration was pipelined, which gathered all the objects in the $merged_array variable.

Once the for loop finished, the $merged_array would have an array of objects where every object would contain a pair of corresponding items from the $firstNames and $lastNames arrays. Finally, we used an echo command to show the $merged_array on the PowerShell console.

Until now, we have merged simple arrays, but how to merge the custom object arrays?

Merging Custom Object Arrays

To merge two custom object arrays in PowerShell:

  • Create two arrays, each having custom objects, while the custom object has two properties.
  • Use the + operator to merge both arrays created in the first step and store the merged array in a variable.
  • Use the echo command to display the merged array.

This example is similar to the first code snippet we learned in this article, but the array creation differs. Here, we created two arrays ($array1 and $array2); each array contained custom objects that we created using [PSCustomObject]@{} notation. Each custom object had two properties called "FirstName" and "LastName".

Then, we used the + operator to merge both arrays and stored it in the $merged_array, which was further used with echo to show on the console. Note that you can use this code snippet and use different ways we learned in this article to merge $array1 and $array2.

To get unique values, let’s use the Select-Object and Sort-Object cmdlets with the -Unique parameter.

In the first section, We have already learned the Select-Object, Sort-Object cmdlets, and -Unique parameter.

That’s all about merge arrays in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *