tags:

views:

1289

answers:

1

Hi, 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?

+5  A: 

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:

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.

dangph
How do you filter the items?
Mark Ingram
@Mark, can you give some more information about how you want to decide what files to remove. Also, what does Get-ResourceFiles return?
dangph
I've got a text file with relative paths in it. After I've enumerated a dir, I want to check if it exists in the file, and if it doesn't exist, remove it from the list.Get-ResourceFiles just returns a path as a string
Mark Ingram
@Mark, I would do something like this: "$newFiles = $oldFiles | where {Test-Path $_}". It might require some tweaking because it assumes all the paths are relative to the current directory.
dangph
@Mark, if you still have problems, post another stackoverflow question. Give plenty of details. Explain precisely what you want the code to do.
dangph