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
Add-Member cmdlet do in PowerShell when working with objects?Add-Member is used to add new properties or methods to an existing object without creating a new object.Add-Member.Age with value 30 to an existing object $person?Add-Member are -InputObject, -MemberType, -Name, and -Value.NoteProperty is the correct member type for adding simple properties. The property name is specified with -Name.$obj = New-Object PSObject
Add-Member -InputObject $obj -MemberType NoteProperty -Name Color -Value 'Red'
Write-Output $obj.Color
Add-Member cmdlet adds a property named Color with value 'Red' to the object $obj.Write-Output $obj.Color accesses the added property and prints its value, which is Red.Height to $obj:$obj = New-Object PSObject
Add-Member -InputObject $obj -MemberType NoteProperty -Property Height -Value 180
Write-Output $obj.Height
-Name, not -Property. Using -Property causes an error.$obj is correctly created. The value 180 can be a number. Write-Output can access added properties if correctly added.$car with properties Make and Model. You want to add a new property Year only if it does not already exist. Which script correctly does this?$car.PSObject.Properties.Name -contains 'Year' checks if the property exists. The -not negates it to add only if missing.Add-Member adds it with value 2023. This avoids errors from duplicate properties.Pass the test and this pattern moves unknown