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 ArrayList
. But the following doesn't work for me:
$temp = Get-ResourceFiles $resourceFiles = New-Object System.Collections.ArrayList($temp)
Where $temp
is an Array.
How can I achieve that?
We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.
What is PowerShell Arraylist. We can use an ArrayList to store a list of items in PowerShell. Unlike array, arraylist's length is not fixed, it can changed. One difference between array and ArrayList is, An array is strongly types, that means array can store only specific type elements.
To create an array of a specific type, use a strongly typed collection: PS > $list = New-Object Collections. Generic. List[Int] PS > $list.
To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.
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.
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
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