9

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.

Necoras
  • 6,743
  • 3
  • 24
  • 45
idMaxCZ
  • 93
  • 1
  • 1
  • 5

2 Answers2

13

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
Loïc MICHEL
  • 24,935
  • 9
  • 74
  • 103
  • Thanks! this is exactly what I need (update Value 'Home' to 'Elsewhere'). It working, but I totally don't know why. You updated variable $col (to 'elsewhere') but change was written to $rec array. Can you quick explain why? There is some inner relation. – idMaxCZ Apr 15 '15 at 11:15
  • $rec is a subset of the collection (all records where assignment is set to home). Modifying this subset will indeed modify the whole collection – Loïc MICHEL Apr 15 '15 at 11:25
  • Thank you, so $rec is another reference to same object? Not copy of object. Like references to objects in heap in C#. Correct? – idMaxCZ Apr 15 '15 at 11:51
1

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.

Jon Hill
  • 23
  • 4