0

I create an ArrayList and add one single element to it. Where does the zero at index 0 come from? What would be a best practice to add an element without adding the ominous zero?

function Get-List() {
    $some_list = [System.Collections.ArrayList]@()
    $some_list.Add(@{
        'some'='a'
        'data'='b'
        'added'='c'
    })
    return $some_list
}


(Get-List).Count # This is 2
(Get-List)[0] # This is an int32 zero
(Get-List)[1] # This is the object I expected at index 0
  • 3
    I think this is a typical powershell "problem". A return in a powershell function will return every single output. The 0 is comming from the add method. The add method will return the index where the value was added. If you use out-null it will not be there anymore. Read about the return a little bit more [here](https://stackoverflow.com/questions/10286164/function-return-value-in-powershell) – guiwhatsthat Oct 04 '18 at 07:45
  • And additional why are you using an arraylist? I think in this case the hashtable would fit better – guiwhatsthat Oct 04 '18 at 07:50
  • Thank you for your help. I understand the problem now and can work around it. :-) I actually wanted to use a simple array. But since that is fixed size I used an ArrayList instead. In my use-case I need to add an amount of users to an array and later iterate through them. As I understand a hashtable consists of key-value-pairs which I do not need in this case. – Foxglove Amberheart Oct 04 '18 at 07:55
  • Added the commetn as an answer to "close" the question – guiwhatsthat Oct 04 '18 at 07:58
  • The `ArrayList.Add()` method ouputs the index of the added element, which is then automatically returned by the function. Suppressing that output removes it from the returned result. – Ansgar Wiechers Oct 04 '18 at 08:17
  • Your code has another problem, though. PowerShell automatically unrolls enumerable lists when returning them. When the caller then collects the returned result it becomes either `$null`, a single value, or a regular array, depending on whether 0, 1 or more values are returned. Example: if the ArrayList contained only a single string "abc" `(Get-List)[0]` would produce "a", not "abc". Prepend the returned value with a comma to avoid this ([related](https://stackoverflow.com/q/40220590/1630171), [also related](https://stackoverflow.com/q/52361118/1630171)). – Ansgar Wiechers Oct 04 '18 at 08:21

1 Answers1

3

I think this is a typical powershell "problem". A return in a powershell function will return every single output. The 0 is comming from the add method. The add method will return the index where the value was added. If you use out-null it will not be there anymore. Read about the return a little bit more here

guiwhatsthat
  • 2,349
  • 1
  • 12
  • 24