【问题标题】:Powershell Object properties get overwritten when new objects added to an array [duplicate]将新对象添加到数组时,Powershell对象属性被覆盖[重复]
【发布时间】:2022-01-11 09:55:51
【问题描述】:

这是我的代码:

$problems = New-Object System.Collections.ArrayList

$problemObj = New-Object psobject -Property @{
    problemName        = "abc"
    problemDescription = $null
}

$problemObj.problemDescription = "def"
$problems.Add($problemObj)

$problemObj.problemDescription = "ghi"
$problems.Add($problemObj)

$problems

这是输出:

problemName problemDescription
----------- ------------------
abc         ghi
abc         ghi

我不明白出了什么问题以及为什么第一个成员会被修改。有什么想法吗?

谢谢,

【问题讨论】:

标签: powershell


【解决方案1】:

您不是在创建新对象 - 您是在多次修改和重新添加 相同 对象到列表中。

解决此问题的常见模式是重用 字典 作为模板,然后转换为 [pscustomobject] 以基于它创建新对象:

$problems = New-Object System.Collections.ArrayList

# Create ordered dictionary to function as object template
$problemTemplate = [ordered]@{
    problemName        = "abc"
    problemDescription = $null
}

# modify template
$problemTemplate.problemDescription = "def"

# create new object, add to list
$problemObj = [pscustomobject]$problemTemplate
$problems.Add($problemObj)

# modify template again
$problemTemplate.problemDescription = "ghi"

# create another object, add to list
$problemObj = [pscustomobject]$problemTemplate
$problems.Add($problemObj)

$problems

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 2015-03-06
    • 2022-01-20
    • 2021-11-09
    • 2021-03-22
    • 1970-01-01
    • 2013-01-03
    相关资源
    最近更新 更多