【发布时间】:2021-03-15 12:14:27
【问题描述】:
我创建了一个带有一些属性的 PSCustom 对象并将其添加到集合中
总之喜欢
$Collection = @()
foreach ($item in $items)
{
$obj = New-Object PSCustomObject
$obj | Add-Member -NotePropertyName Property1 -NotePropertyValue ""
$obj | Add-Member -NotePropertyName Property2 -NotePropertyValue ""
$obj | Add-Member -NotePropertyName Property3 -NotePropertyValue ""
$Collection += $obj
}
到目前为止还可以,并且可以正常工作。 直到我想从中删除一些东西。 我收到一条消息说 op_substraction 不是方法。
好的,所以我搜索了一下,发现我可以像这样声明集合
$Collection = New-Object System.Collections.Generic.List[System.Object]
我将 += 更改为 $Collection.Add($obj) 现在当我做 $Collection.Remove($obj) 我没有收到错误,但 obj 没有被删除。
我用谷歌搜索了更多,发现 [System.Collections.ArrayList] 首先还有一个信息.. 我有以下代码来删除对象($MyItem 包含不应删除的对象的信息)
foreach ($Item in $Collection)
{
if ($MyItem -notcontains $Item.Value)
{
$Collection.Remove($Item)
}
}
所以如果我这样做,它会给出 $Collection 已更改的错误。 好的,所以我克隆了对象列表。我在 SO 上找到了一些代码并对其进行了一些修改
function clone-Collection($obj)
{
$newobj = New-Object System.Collections.Generic.List[System.Object]
foreach ($oobj in $obj)
{
$nobj = New-Object PsObject
$oobj.psobject.Properties | % { Add-Member -MemberType NoteProperty -InputObject $nobj -Name $_.Name -Value $_.Value }
$newobj.Add($nobj)
}
return $newobj
}
我调用函数并且在函数中一切都很好。 但是 ReturnValue 现在在开头有 0,1,2,...。我不知道为什么。我想压制这个。
我进一步读到here [System.Collections.ArrayList] 已被贬低。
所以我几乎迷路了。 如果是这样,我什至应该使用 ArrayList 我如何摆脱数字 如果我不应该使用 ArrayList 什么是正确的替代方案。 还是我做错了什么?
请帮帮我。
谢谢 问候
【问题讨论】:
-
Add()方法输出数组列表中的索引 (0,1,2..)。您可以使用$null = $newobj.Add($nobj)或[void]$newobj.Add($nobj)隐藏它
标签: powershell arraylist pscustomobject