2

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.

2
  • 3
    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. The problem here is that an array list's .Add() method produces output (the index of the newly added element). Commented Feb 5, 2021 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) Commented Feb 5, 2021 at 21:32

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.