Question:
The Powershell “add-member” command is very useful. I use it to add properties to custom objects. Sometimes I set a member as an array to hold multiple objects. Is it possible to add an ArrayList as a member on a custom object?
Imagine a list of articles has properties “index”, “title”, and “keywords.” In Powershell, you could put this code in a loop:
1 2 3 4 5 6 7 8 |
for($i = 0; $i -lt 100; $i++) { $a = new-object -TypeName PSObject $a | Add-Member -MemberType NoteProperty -Name index -Value $i $a | Add-Member -MemberType NoteProperty -Name title -Value "Article $i" $a | Add-Member -MemberType NoteProperty -Name keywords -Value @() $articles += $a } |
You’d end up with an array, $articles, of Article objects, each with members index, title, and keywords. Furthermore, the keywords member is an array that can have multiple entries:
1 2 3 4 |
$articles[2].keywords += "Stack Exchange", "Powershell", "ArrayLists" $articles[2].keywords[2] Powershell |
This meets most of my needs, but I just don’t like dealing with arrays. ArrayLists are just easier to work with, if only because
1 2 |
$arrayList1.remove("value") |
is so much more intuitive than
1 2 |
$array1 = $array1 |? {$_ new "value"} |
Is there a way with Add-Member to add an ArrayList as a member? Or am I stuck with arrays? If Powershell doesn’t support thi snatively, could I pop in some C# code to make a new class with an ArrayList as a member?
Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$arr = @("one","two","three") $arr.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array $a = new-object -TypeName PSObject [System.Collections.ArrayList]$arrList=$arr $a | Add-Member -MemberType NoteProperty -Name ArrayList -value $arrlist $a.ArrayList one two three $a.ArrayList.remove("one") $a.ArrayList two three |
To add a blank ArrayList to your custom object just use
1 2 |
$a | Add-Member -MemberType NoteProperty -Name ArrayList -value (New-object System.Collections.Arraylist) |