3

I have an interesting problem for a while. Let's say I have the function

function GetAllFiles($creds, $fld){
   $newFiles = New-Object "system.collections.generic.list[string]"
   ... other stuff which adds entires
   return $newFiles
}

On the calling side when I execute

$files = GetAllFiles $creds $fld
$files.Remove("AnExistingEntry")

I get

dir-ls.ps1:Method invocation failed because [System.Object[]] doesn't contain a meth od named 'Remove'.

When I do $newFiles.GetType()

IsPublic IsSerial Name                                     BaseType                
-------- -------- ----                                     --------                
True     True     Object[]                                 System.Array 

How can I make it to be "system.collections.generic.list[string]" back?

Thanks

1 Answer 1

2

That object type doesn't have a "remove" method. I think you're looking at the members of the element:

$files | gm will get you the members of the first element of the array (the pipeline will unroll the array, and you end up doing gm on the first element.

gm -inputobject $files will show you the members of the array, and "remove" is not among the methods of that object type.

Try this on your return statement, and see if it keeps the array intact rather than unrolling it on the return.

return ,$newFiles

Sign up to request clarification or add additional context in comments.

3 Comments

The idea is that I loose the system.collections.generic.list[string] outside of the function
i still get >>> dir-ls.ps1:Method invocation failed because [System.Object[]] doesn't contain a method named 'Remove'.
Powershell will automatically try to "unroll" an array into a string of elements. The comma forces the result to be an array of one element - that one element is your original array. When it "unrolls" the end result is that your original array gets passed, intact, as an element of the array that contained it (if that makes sense).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.