Powershell - 如何编辑自定义对象中的现有 属性
Powershell - how do I edit an existing property in a custom object
我正在寻找如何更新现有 psobject 中的 noteproperty 的方法,例如我有 system.array 个 psobject ($a):
Group Assigment
----- ---------
Group1 Home
Group2 Office
问题是如何将 'Home' 更新为其他内容。
$一个 |通用汽车:
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Assigment NoteProperty System.String Assigment=Office
Group NoteProperty System.String Group=Group1
$a.GetType():
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
感谢您以后的帮助。
不太清楚你的问题是什么:select好的对象或更新它的值?
$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
不过,如果 $rec returns 不止一条记录,我认为这行不通。
例如:
$rec = $col | where {$_.assignment -ne $null}
$rec.assignment = "elsewhere"
理论上应该将每个单独记录的分配设置为 "elsewhere" 但它实际上只是 returns 一个错误,即无法在此对象上找到 属性 "assignment"。我认为要真正发挥作用,您需要:
$recs = $col | where {$_.assignment -ne $null}
foreach ($r in $recs) {
$r.assignment="elsewhere"
}
除非有一种方法可以为给定数组中的每条记录设置一个值,我承认可能存在这种方法。
我正在寻找如何更新现有 psobject 中的 noteproperty 的方法,例如我有 system.array 个 psobject ($a):
Group Assigment
----- ---------
Group1 Home
Group2 Office
问题是如何将 'Home' 更新为其他内容。
$一个 |通用汽车:
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Assigment NoteProperty System.String Assigment=Office
Group NoteProperty System.String Group=Group1
$a.GetType():
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
感谢您以后的帮助。
不太清楚你的问题是什么:select好的对象或更新它的值?
$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
不过,如果 $rec returns 不止一条记录,我认为这行不通。
例如:
$rec = $col | where {$_.assignment -ne $null}
$rec.assignment = "elsewhere"
理论上应该将每个单独记录的分配设置为 "elsewhere" 但它实际上只是 returns 一个错误,即无法在此对象上找到 属性 "assignment"。我认为要真正发挥作用,您需要:
$recs = $col | where {$_.assignment -ne $null}
foreach ($r in $recs) {
$r.assignment="elsewhere"
}
除非有一种方法可以为给定数组中的每条记录设置一个值,我承认可能存在这种方法。