Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - how do I edit an existing property in a custom object

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.

like image 811
idMaxCZ Avatar asked Apr 15 '15 07:04

idMaxCZ


People also ask

How do I add a property to a PowerShell object?

The Add-Member cmdlet lets you add members (properties and methods) to an instance of a PowerShell object. For instance, you can add a NoteProperty member that contains a description of the object or a ScriptMethod member that runs a script to change the object.

How do I set properties in PowerShell?

The Set-ItemProperty cmdlet changes the value of the property of the specified item. You can use the cmdlet to establish or change the properties of items. For example, you can use Set-ItemProperty to set the value of the IsReadOnly property of a file object to $True .

What is PSObject in PowerShell?

A PSObject is very much like a hashtable where data is stored in key-value pairs. You can create as many key-value pairs as you like for each PSObject .

What is a NoteProperty PowerShell?

NoteProperties are generic properties that are created by Powershell (as opposed to properties that are inherited from a specific dotnet object type).


1 Answers

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
like image 195
Loïc MICHEL Avatar answered Nov 15 '22 08:11

Loïc MICHEL