Concept Flow - Adding properties to objects
Create object
Add new property
Property added to object
Use updated object
Start with an object, add a new property to it, then use the updated object with the new property.
$obj = New-Object PSObject $obj | Add-Member -MemberType NoteProperty -Name 'Age' -Value 30 $obj.Age
| Step | Action | Object State | Output |
|---|---|---|---|
| 1 | Create empty object $obj | Object with no properties | |
| 2 | Add property 'Age' with value 30 | Object with property Age=30 | |
| 3 | Access $obj.Age | Object unchanged | 30 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 |
|---|---|---|---|---|
| $obj | null | Empty object | Object with Age=30 | Object with Age=30 |
| $obj.Age | null | Error | 30 | 30 |
Create an object with New-Object PSObject Add a property using Add-Member -MemberType NoteProperty -Name 'Prop' -Value val Access the property with $obj.Prop Add-Member modifies the original object Accessing a property before adding it causes an error