简体   繁体   English

当新对象添加到数组时,Powershell Object 属性被覆盖

[英]Powershell Object properties get overwritten when new objects added to an array

Here is my code:这是我的代码:

$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

And here is the output:这是 output:

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

I don't get what's wrong and why the first member gets modified.我不明白出了什么问题以及为什么第一个成员被修改。 Any idea?任何想法?

Thanks,谢谢,

You're not creating new objects - you're modifying and re-adding the same object to the list multiple times.您不是在创建新对象 - 您是在多次修改和重新添加相同的 object 到列表中。

A common pattern for solving this is to re-use a dictionary as a template, then cast to [pscustomobject] to create new objects based on it:解决此问题的常见模式是重新使用字典作为模板,然后转换为[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM