PowerShell function for adding elements to an array

后端 未结 2 1798
甜味超标
甜味超标 2021-01-16 05:31

I\'m still quite new to PowerShell and am trying to create a few functions that weaves together for creating and administrating an array. And I\'m having some problems with

2条回答
  •  误落风尘
    2021-01-16 05:41

    Arrays in .NET don't directly support insertion and they are normally fixed size. PowerShell does allow for easy array resizing but if the array gets large and you're appending (causing a resize) a lot, the performance can be bad.

    One easy way to do what you want is to create a new array from the pieces e.g.:

    if ($index -eq 0) {
        $MainArray = $add,$MainArray
    }
    elseif ($index -eq $MainArray.Count - 1) {
        $MainArray += $add
    }
    else {
        $MainArray = $MainArray[0..($index-1)], $add, $MainArray[$index..($MainArray.Length-1)]
    }
    

    But that is kind of a spew. I would use a List for this, which supports insertion and is more efficient than an array.

    $list = new-object 'System.Collections.Generic.List[object]'
    $list.AddRange((1,2,3,4,5))
    $list.Insert(2,10)
    $list
    

    And if you really need an array, call the $list.ToArray() method when you're done manipulating the list.

提交回复
热议问题