1

I noticed the following behaviour in PowerShell 5.1 when returning Arrays and ArrayLists from functions:

Function A {
    [Array]$data = @()
    $data += 4
    $data += 5
    $data += 6
    return $data
}

$data = A

After calling the function A $data now contains 3 Elements: {4, 5, 6}.

Function B {
    [System.Collections.ArrayList]$data = @()
    $data.Add(4)
    $data.Add(5)
    $data.Add(6)
    return $data
}

$data = B

After calling the function B $data now contains 6 Elements: {0, 1, 2, 4, 5, 6}.

The first 3 Elements are the indices of the ArrayList $data in the function B. Why exactly does PowerShell behave this way and how can I return ArrayLists "correctly" from functions, meaning that $data would only contain the elements {4, 5, 6}?

I think this question is might be related to the first answer of this post Returning ArrayList from Function/Script, which mentions that outputting collections (not just arrays) causes PowerShell to enumerate them by default.

dan-kli
  • 568
  • 2
  • 13
  • 2
    In short: any output - be it from a command or a .NET method call - that is neither captured nor redirected (sent through the pipeline or to a file) is _implicitly output_. To simply _discard_ such output, it's best to use `$null = ...`; see [this answer](https://stackoverflow.com/a/55665963/45375). The problem here is that an array list's `.Add()` method produces output (the index of the newly added element). – mklement0 Feb 05 '21 at 21:27
  • 2
    What happens when you write `$data.Add(4)` in the console? You'll see that it _outputs_ the index, which will end up as part of the function `B` output. Fix: `$null = $data.Add(4)` – zett42 Feb 05 '21 at 21:32

0 Answers0