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.