0

I am very much puzzled with the way PowerShell is behaving with the arrays . In the below code I am adding three entries in the an array and when I check in the function it does give me the array.Count as 3, which is very much on the expected lines. Now I call the function at a different place in the code and the element count just doubles from 3 to 6. I am sure doing something wrong here. Anyone has any idea/thoughts?

function ReadAPEnvInfoFrom () {
$pathList = New-Object System.Collections.ArrayList
    $pathList.Add("aaa")
    $pathList.Add("bbb")
    $pathList.Add("ccc")

    Write-Host 'The count' $pathList.Count
    # returns 3 
    return $pathList
}

cls
$Array = New-Object System.Collections.ArrayList 
$Array = ReadAPEnvInfoFrom
Write-Host 'The count' $Array.Count
# returns 6
5
  • 1
    Show minimal reproducible example. Where $pathList defined? Commented Jul 27, 2016 at 21:59
  • $Array should probably be $pathList in your sample code. If I run it the count is increased by 3 each time the function is called, just as expected. Commented Jul 27, 2016 at 22:10
  • Asgar : I just updated the code (for the issue ) ..apologizes for the initial miss from my side . I am sure I am missing something here . Commented Jul 27, 2016 at 22:36
  • 1
    $pathList.Add("xxx") -> [void]$pathList.Add("xxx"), also no need for $Array = New-Object System.Collections.ArrayList as you replace $Array value on next line. And return $pathList -> return ,$pathList if you actually want to return ArrayList from function but not its elements. Commented Jul 27, 2016 at 22:39
  • P.S. If you want to notify previous commenter, then you should use this @Himanshu notation. Commented Jul 27, 2016 at 22:49

1 Answer 1

1

To explain - each of your calls to the Add() method on the ArrayList is placing an index number onto the pipeline. Even though they are not explicitly being returned, they are included in the value returned by the function. So if you look at the value of $Array, you get:

0
1
2
aaa
bbb
ccc

You can either cast those calls to [void] at @PetSerAl is doing in the comment, or personally I prefer either assigning them to $null:

$null = $pathList.Add("aaa") 

or to pipe the output to Out-Null:

$pathList.Add("aaa") | Out-Null

It comes down to personal preference there. ;)

Sign up to request clarification or add additional context in comments.

1 Comment

Another option is to redirect undesired output: $pathList.Add("aaa") > $null. The return behavior of PowerShell functions is explained in the documentation, BTW.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.