How do I dynamically add elements to arrays in PowerShell? How do I dynamically add elements to arrays in PowerShell? powershell powershell

How do I dynamically add elements to arrays in PowerShell?


$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 are going to play with a dynamic amount of items, a more precise solution might be using the List:

$testArray = New-Object System.Collections.Generic.List[System.Object]$tempArray = "123", "321", "453"foreach($item in $tempArray){    $testArray.Add($item)}

Note: In this case you get the power of the List from .Net, so you can easily apply linq, merge, split, and do anything which you'd do with the List in .Net