Powershell - how edit existing property in custom object

天涯浪子 提交于 2019-12-09 04:26:28

It's not really clear what is your problem : select the good object or update it's value ?

$col=@() 
$props=@{"group"="group1";"assignment"="home"}
$col += new-object pscustomobject -property $props
$props2=@{"group"="group2";"assignment"="office"}
$col += new-object pscustomobject -property $props2

#select object with home assignment
$rec=$col | where {$_.assignment -eq "home"}
#replace the value
$rec.assignment="elsewhere"

#display collection with updated value
$col

I don't think this works if $rec returns more than one record, though.
For example:

$rec = $col | where {$_.assignment -ne $null}
$rec.assignment = "elsewhere"

In theory that should set every individual record's assignment to "elsewhere" but it really just returns an error that the property "assignment" cannot be found on this object. I think for this to really work you'd need:

$recs = $col | where {$_.assignment -ne $null}
foreach ($r in $recs) {
 $r.assignment="elsewhere"
}

Unless there's a way to set a value to every record in a given array, which I freely admit there may be.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!