Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically add elements to arrays in PowerShell?

Tags:

I don't have much PowerShell experience yet and am trying to teach myself as I go along.

I'm trying to make some proof of concept code for a bigger project. The main goal here is too dynamically create and add elements to an array using a function.

Here is my code:

$testArray = @() function addToArray($Item1) {     $testArray += $Item1     "###" }  $tempArray = "123", "321", "453" $foldertest = "testFolder"  foreach($item in $tempArray) {     addToArray $item } "###" 

Every time the function finishes the array becomes empty. Bear in mind most of my programming experience comes from Java, PHP, some C and C++ just to name a few, if I did this in PHP (adjusting the language syntax of course) this would have worked fine.

like image 274
LuckyFalkor84 Avatar asked Nov 10 '12 01:11

LuckyFalkor84


People also ask

How do you add items to an array dynamically?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.

How do I add values to an array in PowerShell?

To add value to the array, you need to create a new copy of the array and add value to it. To do so, you simply need to use += operator. For example, you have an existing array as given below. To add value “Hello” to the array, we will use += sign.

Can be used to add elements to the array in PowerShell?

You can use the += operator to add an element to an array. The following example shows how to add an element to the $a array. When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value.

Are PowerShell arrays dynamic?

Arrays were never meant to be operated dynamically. Every time you resize an array, it creates a new one under the hood. So you get the overhead proportional to its size.


2 Answers

$testArray = [System.Collections.ArrayList]@() $tempArray = "123", "321", "453"  foreach($item in $tempArray) {     $arrayID = $testArray.Add($item) } 
like image 56
Angel Abad Cerdeira Avatar answered Sep 22 '22 16:09

Angel Abad Cerdeira


The problem is one of scope; inside your addToArray function change the line to this:

$script:testArray += $Item1 

...to store into the array variable you are expecting.

like image 32
Michael Sorens Avatar answered Sep 22 '22 16:09

Michael Sorens