How do I dynamically add elements to arrays in PowerShell?

前端 未结 4 1587
执念已碎
执念已碎 2021-02-12 15:10

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 g

相关标签:
4条回答
  • 2021-02-12 15:37

    Instead of re-creating the array in each loop iteration (which is basically what's happening each time you add to it), assign the result of the the loop to a variable:

    $testArray = foreach($item in $tempArray)
    {
        addToArray $item
    }
    
    0 讨论(0)
  • 2021-02-12 15:42
    $testArray = [System.Collections.ArrayList]@()
    $tempArray = "123", "321", "453"
    
    foreach($item in $tempArray)
    {
        $arrayID = $testArray.Add($item)
    }
    
    0 讨论(0)
  • 2021-02-12 15:58

    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.

    0 讨论(0)
  • 2021-02-12 16:02

    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

    0 讨论(0)
提交回复
热议问题