PowerShell Script to Merge Two Arrays Easily
$merged = $array1 + $array2, which combines both arrays into one.Examples
How to Think About It
+ joins arrays by placing elements of the second array after the first.Algorithm
Code
$array1 = 1, 2, 3 $array2 = 4, 5, 6 $merged = $array1 + $array2 Write-Output $merged
Dry Run
Let's trace merging [1, 2, 3] and [4, 5, 6] through the code
Define first array
$array1 = 1, 2, 3
Define second array
$array2 = 4, 5, 6
Merge arrays
$merged = $array1 + $array2 results in [1, 2, 3, 4, 5, 6]
| Step | Action | Result |
|---|---|---|
| 1 | Set $array1 | [1, 2, 3] |
| 2 | Set $array2 | [4, 5, 6] |
| 3 | Merge with + | [1, 2, 3, 4, 5, 6] |
Why This Works
Step 1: Using the plus operator
The + operator in PowerShell concatenates arrays by appending the second array's elements to the first.
Step 2: Creating a new array
The merged array is a new array that holds all elements from both original arrays in order.
Step 3: Outputting the result
Using Write-Output prints each element of the merged array on its own line.
Alternative Approaches
$merged = @($array1 + $array2) Write-Output $merged
$merged = $array1 $merged += $array2 Write-Output $merged
$merged = [System.Linq.Enumerable]::Concat($array1, $array2) | ForEach-Object { $_ }
Write-Output $mergedComplexity: O(n + m) time, O(n + m) space
Time Complexity
Merging arrays requires copying all elements from both arrays, so time grows linearly with the total number of elements.
Space Complexity
A new array is created to hold all elements, so space usage grows with the combined size of both arrays.
Which Approach is Fastest?
Using the plus operator + is simple and efficient for most cases; .NET methods may add overhead but offer flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Plus operator (+) | O(n + m) | O(n + m) | Simple and readable merging |
| += operator | O(n + m) | O(n + m) | Incremental merging modifying first array |
| .Concat() method | O(n + m) | O(n + m) | Using .NET methods, advanced scenarios |
$merged = $array1 + $array2 for the simplest and most readable array merge in PowerShell.($array1, $array2) which creates a nested array instead of merging.