Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell add-member. Add a member that's an ArrayList?

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:

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:

$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

$arrayList1.remove("value")

is so much more intuitive than

$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?

like image 702
Bagheera Avatar asked Dec 04 '22 06:12

Bagheera


1 Answers

$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

$a | Add-Member -MemberType NoteProperty -Name ArrayList -value (New-object System.Collections.Arraylist)
like image 79
Cole9350 Avatar answered Dec 28 '22 23:12

Cole9350