Site icon Dotnet Helpers

How to combine the elements of two arrays using Powershell

An array is a data structure that is designed to store a collection of items. The items can be the same type or different types. 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 you plan to add and remove data from an array frequently, the System. Collections.ArrayList class provides a more dynamic alternative. In this post, we are going to discuss the different way of scenarios for combining the two Array and output with a single Array

Example 1:

If you want to join arrays in Powershell, especially if you don’t know if one or more of the objects you are joining are arrays or single objects, combine them with the addition ‘+’ operator and cast the first item as an array.

OUTPUT:

Example 2:

If you like to join two arrays by fetching the elements from each array one by one and not have them combined or simply merged.

OUTPUT:

Example 3:

In this example, you can see how to Combine Individual Items From Separate Arrays Into a Third Array. Below example, we having two arrays, one with a list of first names and a second with a list of last names. The third Array will have the result of combining the first name and the last name that reside at the same index position in their respective arrays into a third array (combine them and output them with column headers). Example as follows:

OUTPUT:

What do you think?

I hope you have an idea of How to join the elements of two arrays using Powershell. I would like to have feedback from the readers of my post. Your valuable feedback, question, or comments about this article are always welcome.

Exit mobile version