首页 > 解决方案 > Powershell 克隆对象 ArrayList

问题描述

我创建了一个带有一些属性的 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

$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,...。我不知道为什么。我想压制这一点。

我进一步在这里读到[System.Collections.ArrayList] 已被贬低。

所以我几乎迷路了。如果是这样,我什至应该使用 ArrayList 如果我不应该使用 ArrayList,我该如何摆脱数字,什么是正确的替代方案。还是我做错了什么?

请帮我。

谢谢问候

标签: powershellarraylistpscustomobject

解决方案


正如所评论的,Add()ArrayList 上的方法输出添加新项目的索引。要抑制此输出,只需执行$null = $newobj.Add($nobj)[void]$newobj.Add($nobj)

至于Remove()通用列表中的方法,如果我指定要正确删除的对象,它对我有用:

$Collection = New-Object System.Collections.Generic.List[System.Object]
$items = 'foo', 'bar', 'baz'
foreach ($item in $items) {
    $obj = New-Object PSCustomObject
    $obj | Add-Member -NotePropertyName Property1 -NotePropertyValue $item
    $obj | Add-Member -NotePropertyName Property2 -NotePropertyValue ""
    $obj | Add-Member -NotePropertyName Property3 -NotePropertyValue ""
    $Collection.Add($obj)

    # or simply do
    # $Collection.Add([PsCustomObject]@{Property1 = $item; Property2 = ''; Property3 = ''})
}

要创建集合的副本,您可以执行以下操作:

$newCollection = [PsCustomObject[]]::new($Collection.Count)
$Collection.CopyTo($newCollection)

从原始 $Collection 中删除一个对象:

$obj = $Collection | Where-Object {$_.Property1 -eq 'bar'}
[void]$Collection.Remove($obj)
$Collection

输出:

Property1 Property2 Property3
--------- --------- ---------
foo                          
baz                          

推荐阅读