How to Add Items to an Array

An array, once created, stays the same size forever, and so in order to make it larger, you need to copy it to a new array, and delete the original.

Array Addition

PowerShell can add two arrays together using the “+” operator, which hides the complexity of what the system is actually doing. For instance, if you make two test arrays like this:

$first = @('Zero', 'One')
$second = @('Two', 'Three')

You can then add them together using just:

PS> $first + $second

This will make a new array with all four values, and output the results. Note, however, that it will not give this new array a new name. To do that, we use the += operator.

Plus Equals for Combining Arrays

Instead of using the “+” operator in the above example, we could have used the “+=” operator, which will give us a whole new array:

$first += 'Two, Three'

The command looks simple, but it is hiding what PowerShell is actually doing here. It is copying all of the values from $first, and making a new array that includes the extra values. It then deletes the original array.

This is somewhat problematic because it is computationally expensive. With small arrays, you might not notice, but with large amounts of data this method can quickly lock up your system.

PowerShell
Array

Comments

Leave a Comment

All fields are required. Your email address will not be published.