1

I have a simple repro where I define an array and return it in a function. My script simply calls this function, casting the result to a variable, then prints each element in that variable. What I don't understand is why I'm getting empty entities at the beginning of the array. This only happens if the array is created in a Function and returned.

Code:

function Get-Things
{
       $stuff = new-object system.collections.arraylist
       $stuff.Add("Zeroth")
       $stuff.Add("First")
       $stuff.Add("Second")
       $stuff.Add("Third")
               

    return $stuff
}

$stuffs = Get-Things

foreach($thingy in $stuffs)
{
    Write-Host($thingy)
} 

Expected result:

Zeroth
First
Second
Third

Actual result:

0
1
2
3
Zeroth
First
Second
Third
jamesosb
  • 11
  • 1
  • 5
    The `.Add()` method on ArrayList returns the index number of each element added. You can suppress that output by using `$null = $stuff.Add(..)` or `$stuff.Add(..) | Out-Null` – Theo May 02 '22 at 21:12

0 Answers0