0

I have a powershell script which uses Arraylist and the same syntax works for some data and sometimes it throws error for different data.

$parsed_teamarrlist = New-Object System.Collections.ArrayList

After adding data $parsed_teamarrlist and writing to file , I try to clear the data in arraylist

if($parsed_teamarrlist) {
      $parsed_teamarrlist.Clear()
    }

During execution, for some data, it does not throws error, where as sometimes it throws the below error for different data.

Method invocation failed because [System.String] does not contain a method named 'Clear'.
+           $parsed_teamarrlist.Clear()
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
Joe_12345
  • 589
  • 2
  • 7
  • 19
  • only possible way this could happen would be if you reassigned a string to that variable or the variable was previously coerced to be a string. you need to add more code to get a better understanding of what is wrong with it – Santiago Squarzon Jul 17 '23 at 03:30
  • 3
    With the limitted info available, I guess it concernes a classic PowerShell issue where [4a.. PowerShell unrolls single item collections](https://stackoverflow.com/a/69644807/1701026) – iRon Jul 17 '23 at 05:48
  • 1
    You may have only one item in the list and often PS will convert to a singleton. Adding @() around the object will force to an array : @($parsed_teamarrlist).Clear() – jdweng Jul 17 '23 at 12:40
  • @iRon - Your solution works, at times there is single value in the arraylist . I had to convert it to Array and clear it. It worked. Can you please write as solution, so that I can accept the answer – Joe_12345 Jul 17 '23 at 13:33

0 Answers0