【发布时间】:2025-11-29 08:55:01
【问题描述】:
我的目标是创建一个自定义数据对象,其中包含两个离散变量(fooName 和 fooUrl)和一个 fooChildren 列表,每个列表项都有两个离散变量变量 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 显示
fooName : foo-a-rama
fooUrl : https://1.2.3.4
fooChildrenList : {}
如何将 System.Collections.ArrayList 添加到 PowerShell 自定义对象?
【问题讨论】:
标签: powershell arraylist pscustomobject