Growing Arrays Dynamically in PowerShell

We initiate how many elements an array has at the beginning. What if you need more memory space allocated for additional elements? In this tutorial, you will learn how to grow arrays dynamically in Windows PowerShell.

Setup

If you have not already done so, open Windows PowerShell ISE.

The Concept…

Usually, arrays are allocated as contiguous spaces in memory because their sizes are fixed based on how many elements you say they are to contain when first created. This particular arrangement makes arrays highly efficient data structures, especially for sequential read operations. Unfortunately, the downside is that if you want to grow the array so that it is capable of storing more elements than you created it to store, you typically have to create a new array and then copy each element of the old array into the new.

Adding elements to an existing array in Windows PowerShell is easy. You will be using the same += operator that you use to increment the value of a numerical data type by a certain amount. In the following code snippet, first I create a n array with five values and use a for loop to display the values. Next, we use the += operator to add another five values to the array. Then I use a for loop again to display the values one more time.

Example


#Growing Arrays Dynamically
 
$arr = 2,3,5,7,11
Write-Host "First time around..."
for ($i = 0; $i -lt $arr.length; $i++){
    Write-Host $arr[$i]
}
$arr += 13,17,19,29
Write-Host "Second time around..."
for ($i = 0; $i -lt $arr.length; $i++){
    Write-Host $arr[$i]
}

  

Copy and Try it

The output is as follows:

As you can see, the first time, the array only has the 5 elements with it, the second time around, the array has the 5 as well as the next five printed out, the array successfully had the elements appended to it with the (+=) operator.

Remarks last but not least…

There are many applications to today's lesson, it just depends on what you are looking for in terms of functionality. Thank you for being a valued reader. Join us next time for more PSH tutorials! Till then