Array method question

I have a script where I initialise an array thus:

$global:SearchResults = [System.Collections.Generic.List[object]]::new()

Then through the script I wanted accumulate search results by doing:

$global:SearchResults.addrange(@($CurrentSearch))

The weird thing is that the first time the above line is executed, it correctly adds the objects to the global variable. However, the second time it tries to run the above line to add more objects I get the error:

Method invocation failed because [System.Management.Automation.PSCustomObject] does not contain a method named ‘addrange’.

Why would the method be available only the first time it is run?

Hi David,

Do you assign a value to $global:SearchResults anywhere else in your script? I am unable to replicate the issue with the given code. It seems that the Base Type for $global:SearchResults is changing from System.Object to System.Management.Automation.PSCustomObject, which doesn’t have an AddRange method.

I just looked and I do a sort on that object which drops the methods. Not sure why but I can fix that.

David,

Sort-object returns a PSObject, but, you can use type casting to explicitly define the output type by converting results into [System.Collections.Generic.List[object]] like this:

$global:SearchResults = [System.Collections.Generic.List[object]]($global:SearchResults | sort -Descending)

Genius! Thanks heaps for that

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.