How to create an ArrayList from an Array in PowerShell?

后端 未结 2 1886
孤独总比滥情好
孤独总比滥情好 2021-02-01 05:36

I\'ve got a list of files in an array. I want to enumerate those files, and remove specific files from it. Obviously I can\'t remove items from an array, so I want to use an

相关标签:
2条回答
  • 2021-02-01 06:07

    Probably the shortest version:

    [System.Collections.ArrayList]$someArray
    

    It is also faster because it does not call relatively expensive New-Object.

    0 讨论(0)
  • 2021-02-01 06:09

    I can't get that constructor to work either. This however seems to work:

    # $temp = Get-ResourceFiles
    $resourceFiles = New-Object System.Collections.ArrayList($null)
    $resourceFiles.AddRange($temp)
    

    You can also pass an integer in the constructor to set an initial capacity.

    What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?

    Edit:

    It seems that you can use the array constructor like this:

    $resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
    

    Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.

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