0
0
PowerShellscripting~10 mins

Adding properties to objects in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
PowerShell
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name 'Age' -Value 30
$obj.Age
Creates an object, adds a property 'Age' with value 30, then outputs the Age property.
Execution Table
StepActionObject StateOutput
1Create empty object $objObject with no properties
2Add property 'Age' with value 30Object with property Age=30
3Access $obj.AgeObject unchanged30
💡 All steps complete, property added and accessed successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
$objnullEmpty objectObject with Age=30Object with Age=30
$obj.AgenullError3030
Key Moments - 2 Insights
Why does $obj.Age return an error before adding the property?
Before Step 2 in the execution_table, the object has no 'Age' property, so accessing $obj.Age fails.
Does Add-Member change the original object or create a new one?
Add-Member modifies the original object in place, as shown by the object state change from Step 1 to Step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at Step 3?
Anull
B30
CError
DEmpty string
💡 Hint
Check the Output column at Step 3 in the execution_table.
At which step does the object gain the 'Age' property?
AStep 2
BStep 1
CStep 3
DNever
💡 Hint
Look at the Object State column changes between Step 1 and Step 2.
If you tried to access $obj.Age before Step 2, what would happen?
AIt would output 30
BIt would output null
CIt would cause an error
DIt would output an empty string
💡 Hint
Refer to the key_moments explanation about accessing properties before they exist.
Concept Snapshot
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
Full Transcript
This example shows how to add a property to a PowerShell object. First, we create an empty object with New-Object PSObject. Then, we add a new property called 'Age' with the value 30 using Add-Member. Finally, we access the Age property, which outputs 30. Before adding the property, trying to access it would cause an error because it does not exist yet. Add-Member changes the original object by adding the property directly.