我的目标是创建一个具有两个离散变量(fooName
和fooUrl
)和一个fooChildren
列表的自定义数据对象,每个列表项都具有两个离散变量变量{{ 1}}和childAge
。
目前,我有这个:
childName
产生以下内容。到目前为止一切顺利
$fooCollection = [PSCustomObject] @{fooName=""; fooUrl=""; fooChildrenList=@()}
$fooCollection.fooName = "foo-a-rama"
$fooCollection.fooUrl = "https://1.2.3.4"
$fooChild = New-Object -TypeName PSobject
$fooChild | Add-Member -Name childAge -MemberType NoteProperty -Value 6
$fooChild | Add-Member -Name childName -MemberType NoteProperty -Value "Betsy"
$fooCollection.fooChildrenList += $fooChild
$fooChild = New-Object -TypeName PSobject
$fooChild | Add-Member -Name childAge -MemberType NoteProperty -Value 10
$fooChild | Add-Member -Name childName -MemberType NoteProperty -Value "Rolf"
$fooCollection.fooChildrenList += $fooChild
cls
$fooCollection.fooName
$fooCollection.fooUrl
foreach ($fooChild in $fooCollection.fooChildrenList)
{
(" " + $fooChild.childName + " " + $fooChild.childAge)
}
问题:我不喜欢使用foo-a-rama
https://1.2.3.4
Betsy 6
Rolf 10
,因为据我了解,使用+=
会创建+=
的副本(无论如何每次执行$fooCollection.fooChildrenList
时都会显示它所在的状态。
因此,我不想将+=
实现为fooChildrenList
,而是想将@()
实现为fooChildrenList
,以便可以根据需要添加每一行。我已经尝试了多种方式在代码中进行此操作,但是New-Object System.Collections.ArrayList
最终无人居住。例如:
fooChildrenList
$fooCollection = [PSCustomObject] @{fooName=""; fooUrl=""; fooChildrenList = New-Object System.Collections.ArrayList}
$fooCollection.fooName = "foo-a-rama"
$fooCollection.fooUrl = "https://1.2.3.4"
$fooChild.childName = "Betsy"
$fooChild.childAge = 6
$fooCollection.fooChildrenList.Add((New-Object PSObject -Property $fooChild))
$fooChild.childName = "Rolf"
$fooChild.childAge = 10
$fooCollection.fooChildrenList.Add((New-Object PSObject -Property $fooChild))
显示
$fooCollection | get-member
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
fooChildrenList NoteProperty System.Collections.ArrayList fooChildrenList=
fooName NoteProperty string fooName=foo-a-rama
fooUrl NoteProperty string fooUrl=https://1.2.3.4
显示
$fooCollection
如何将System.Collections.ArrayList添加到PowerShell自定义对象?