Powershell - how edit existing property in custom

2019-05-30 05:56发布

问题:

I looking for way how update noteproperty in existing psobject, for example I have system.array of psobjects ($a):

Group                                Assigment
-----                                ---------
Group1                               Home
Group2                               Office

Question is how update 'Home' to something other.

$a | gm:

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

Thank you for future help.

回答1:

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


回答2:

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.