65

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
TylerH
  • 20,799
  • 66
  • 75
  • 101
Milde
  • 2,144
  • 3
  • 17
  • 15
  • 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) – DEberhardt Aug 31 '20 at 15:37

2 Answers2

102

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
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • 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. – TylerH Oct 27 '20 at 19:24
  • 1
    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` – Keith Hill Oct 28 '20 at 20:49
  • 1
    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. – TylerH Oct 28 '20 at 21:00
26

Two more options :)

Pipe to out-null

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

Assign the result to $null:

$null = $myArrayList.Add("test")
Bakudan
  • 19,134
  • 9
  • 53
  • 73
Shay Levy
  • 121,444
  • 32
  • 184
  • 206