70

is there a way to supress the return value (=Index) of an ArrayList in Powershell (using System.Collections.ArrayList) or should I use another class?

$myArrayList = New-Object System.Collections.ArrayList($null)
$myArrayList.Add("test")
Output: 0
1
  • While all options presented here are valid, I personally go for [void] for one simple reason: The need for speed :) Measure-Object is your friend. (There is a good blog article about speed for these things, but I can't find it at the moment, sorry) Commented Aug 31, 2020 at 15:37

2 Answers 2

111

You can cast to void to ignore the return value from the Add method:

[void]$myArrayList.Add("test") 

Another option is to redirect to $null:

$myArrayList.Add("test") > $null
Sign up to request clarification or add additional context in comments.

3 Comments

I've discovered the problem with either of these is that it can't be outputted (e.g. Write-Output) when part of an existing sequence. E.g. I have an arraylist $ADUsersList that I add a record to via .Add(). When I then try to Write-Output $ADUsersList as part of the script, it's blank in my IDE. But as soon as the script is done running, and I just check $ADUsersList for contents, they get printed as I would expect.
I think you have some other issue going on. Try this in PS >= 5 and you'll see it outputs the contents of the list: $l = [System.Collections.ArrayList]::new(); $l.Add("test") > $null; $l
You're right; that does work. Not sure what about my situation is causing the difference (I'm inserting an ordered PSObject record into an ArrayList via [void]$ArrayList.Add($objRecord). It worked if I checked $ArrayList after the script ran, but during the script any Write-Output attempts at displaying $ArrayList's contents failed). Anyway, glad to see I was mistaken. It means debugging w/ ArrayLists is slightly easier than I thought.
28

Two more options :)

Pipe to out-null

$myArrayList.Add("test") | Out-Null  

Assign the result to $null:

$null = $myArrayList.Add("test")

3 Comments

Can you speak to the efficiency of piping to Out-Null versus > $null, or assigning to $null versus casting to [void]? Which of these four is most efficient?
why does arraylist add nulls in the list

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.