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.
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.
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.
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.
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.
$testArray = [System.Collections.ArrayList]@() $tempArray = "123", "321", "453" foreach($item in $tempArray) { $arrayID = $testArray.Add($item) }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With