Table of Contents
Using +
Operator
Use +
operator to merge arrays in PowerShell.
1 2 3 4 5 6 |
$array1 = @("Welcome", "to", "Java2Blog!") $array2 = @("Let's", "learn", "together.") $merged_array = $array1 + $array2 echo $merged_array |
1 2 3 4 5 6 7 8 |
Welcome to Java2Blog! Let's learn together. |
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.
1 2 3 4 5 6 |
$array1 = @("Welcome", "to", "Java2Blog!") $array2 = @("Let's", "learn", "together.") $merged_array = $array2 + $array1 echo $merged_array |
1 2 3 4 5 6 7 8 |
Let's learn together. Welcome to Java2Blog! |
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.
1 2 3 4 5 6 7 |
$array1 = @("How", "are", "You") $array2 = @("What", "are", "you", "learning") $merged_array = $array1 + $array2 $merged_array = $merged_array | Select-Object -Unique $merged_array |
1 2 3 4 5 6 7 8 |
How are You What you learning |
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.
1 2 3 4 5 6 7 |
$array1 = @("How", "are", "You") $array2 = @("What", "are", "you", "learning") $merged_array = $array1 + $array2 $merged_array = $merged_array | Sort-Object -Unique $merged_array |
1 2 3 4 5 6 7 |
are How learning What You |
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.
1 2 3 4 5 6 |
$array1 = @("How", "are", "You") $array2 = @("What", "are", "you", "learning") $array1 += $array2 $array1 |
1 2 3 4 5 6 7 8 9 |
How are You What are you learning |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
$array1 = @("How", "are", "You") $array2 = @("What", "are", "you", "learning") $array1 += $array2 echo "Remove Duplicates by Case-sensitive Check:" echo $array1 | Select-Object -Unique echo "`n" echo "Remove Duplicates by Case-insensitive Check:" echo $array1 | Sort-Object -Unique |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Remove Duplicates by Case-sensitive Check: How are You What you learning Remove Duplicates by Case-insensitive Check: are How learning What You |
-Unique
parameter is case-sensitive while using it with theSelect-Object
cmdlet. On the other hand, it is case-insensitive while using it with theSort-Object
cmdlet.
Further reading:
Using a Comma
Use a comma (,
) to merge two arrays in PowerShell. The merged array must be an array of arrays.
1 2 3 4 5 6 |
$array1 = @(3,8,5) $array2 = @(9,8,7) $merged_array = $array1, $array2 echo $merged_array |
1 2 3 4 5 6 7 8 |
3 8 5 9 8 7 |
Alternatively, merge the arrays as follows if you want to have $array2
followed by the $array1
in the merged array.
1 2 3 4 5 6 |
$array1 = @(3,8,5) $array2 = @(9,8,7) $merged_array = $array2, $array1 echo $merged_array |
1 2 3 4 5 6 7 8 |
9 8 7 3 8 5 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$array1 = @(3,8,5) $array2 = @(9,8,7) $merged_array = $array2, $array1 $flattened_array = $merged_array | ForEach-Object { $_ } echo "Remove Duplicates:" echo $flattened_array | Select-Object -Unique echo "`n" echo "Remove Duplicates in Sorted Output:" echo $flattened_array | Sort-Object -Unique |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Remove Duplicates: 9 8 7 3 5 Remove Duplicates in Sorted Output: 3 5 7 8 9 |
Using AddRange()
Method
Use the AddRange()
method to merge two arrays in PowerShell, but the merged array must be an ArrayList.
1 2 3 4 5 6 7 8 9 10 |
$array1 = 4, 5, 3 $array2 = 4, 5, 6 $merged_array = New-Object System.Collections.ArrayList $merged_array.AddRange($array1) $merged_array.AddRange($array2) $merged_array |
1 2 3 4 5 6 7 8 |
4 5 3 4 5 6 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$array1 = 4, 5, 3 $array2 = 4, 5, 6 $merged_array = New-Object System.Collections.ArrayList $merged_array.AddRange($array1) $merged_array.AddRange($array2) echo "Remove Duplicates:" echo $merged_array | Select-Object -Unique echo "`n" echo "Remove Duplicates in Sorted Output:" echo $merged_array | Sort-Object -Unique |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Remove Duplicates: 4 5 3 6 Remove Duplicates in Sorted Output: 3 4 5 6 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$firstNames = @("Mehvish", "Maryam", "Christopher") $lastNames = @("Ashiq", "Mukhtar", "Daniel") $merged_array = @() $MaxArraySize = [Math]::Max($firstNames.Length, $lastNames.Length) for ($i = 0; $i -lt $MaxArraySize; $i++){ $merged_array+=$firstNames[$i] $merged_array+=$lastNames[$i] } echo $merged_array |
1 2 3 4 5 6 7 8 |
Mehvish Ashiq Maryam Mukhtar Christopher Daniel |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$firstNames = @("Mehvish", "Maryam", "Christopher") $lastNames = @("Ashiq", "Mukhtar", "Daniel") $merged_array = @() $MaxArraySize = [Math]::Max($firstNames.Length, $lastNames.Length) $merged_array = for ($i = 0; $i -lt $MaxArraySize; $i++){ Write-Verbose "$($firstNames[$i]),$($lastNames[$i])" [PSCustomObject]@{ FirstNames = $firstNames[$i] LastNames = $lastNames[$i] } } echo $merged_array |
1 2 3 4 5 6 7 |
FirstNames LastNames ---------- --------- Mehvish Ashiq Maryam Mukhtar Christopher Daniel |
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 $lastNames
arrays. 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$array1 = @([PSCustomObject]@{ FirstName = "John" LastName = "Christopher" }, [PSCustomObject]@{ FirstName = "Priya" LastName = "Mehta" }) $array2 = @([PSCustomObject]@{ FirstName = "Saira" LastName = "Daniel" }, [PSCustomObject]@{ FirstName = "Shruti" LastName = "Mehta" }) $merged_array = $array1 + $array2 echo $merged_array |
1 2 3 4 5 6 7 8 |
FirstName LastName --------- -------- John Christopher Priya Mehta Saira Daniel Shruti Mehta |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
$array1 = @([PSCustomObject]@{ FirstName = "John" LastName = "Christopher" }, [PSCustomObject]@{ FirstName = "Priya" LastName = "mehta" }) $array2 = @([PSCustomObject]@{ FirstName = "Saira" LastName = "Daniel" }, [PSCustomObject]@{ FirstName = "Shruti" LastName = "Mehta" }) $merged_array = $array1 + $array2 echo "Remove Duplicates by Case-sensitive Check:" echo $merged_array | Select-Object -Unique -Property LastName echo "`n" echo "Remove Duplicates by Case-insensitive Check:" echo $merged_array | Sort-Object -Unique -Property LastName |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Remove Duplicates by Case-sensitive Check: LastName -------- Christopher mehta Daniel Mehta Remove Duplicates by Case-insensitive Check: Christopher Daniel Mehta |
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.