1

I am new to powershell an tried a function which generates an array.

function array_create {
    $array = [System.Collections.ArrayList]@()
    $array.Add('hello')
    $array.Add('world')
    return $array
}

$arr = array_create
foreach($a in $arr){
   $a
}

even if I put @() arround the function call the output is

0
1
hello
world

how would I correctly return an array with only values (no numbers) and why does this happen ?

3
  • [void]$array.Add('hello') or $null = $array.Add('hello') Commented May 19, 2020 at 9:37
  • Does this answer your question? Prevent ArrayList.Add() from returning the index Commented May 19, 2020 at 9:40
  • Thanks RoadRunner that actually did answer the question. Sorry Didn't find it before Commented May 19, 2020 at 9:54

1 Answer 1

2

It's because the Add method of ArrayList Class returns an [int] value:

$array = [System.Collections.ArrayList]@()
$array.Add
OverloadDefinitions
-------------------
int Add(System.Object value)
int IList.Add(System.Object value)

Use [void]$array.Add('hello') or $null = $array.Add('hello').

The $array.Add('hello') | Out-Null is possible but not recommended in loops for its negative performance impact.

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

1 Comment

Thanks JosefZ for the hint and the explenation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.