0
0
PowerShellscripting~5 mins

Adding properties to objects in PowerShell

Choose your learning style9 modes available
Introduction
Adding properties to objects lets you store extra information in them. This helps you keep related data together in one place.
You want to add a new detail to an existing object without creating a new one.
You need to store extra information temporarily during a script.
You want to customize objects for reports or output with more fields.
You want to add notes or tags to objects for filtering later.
Syntax
PowerShell
$object | Add-Member -MemberType NoteProperty -Name PropertyName -Value PropertyValue
Use Add-Member to add a new property to an existing object.
NoteProperty is a simple property that holds a value.
Examples
Creates a new object and adds an Age property with value 30.
PowerShell
$person = New-Object PSObject
$person | Add-Member -MemberType NoteProperty -Name Age -Value 30
$person
Adds a Year property to an existing car object.
PowerShell
$car = [PSCustomObject]@{Make='Toyota'; Model='Camry'}
$car | Add-Member -MemberType NoteProperty -Name Year -Value 2020
$car
Adds a Color property and then accesses it.
PowerShell
$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name Color -Value 'Blue'
$obj.Color
Sample Program
This script creates a book object and adds Title, Author, and Pages properties. Then it prints each property.
PowerShell
$book = New-Object PSObject
$book | Add-Member -MemberType NoteProperty -Name Title -Value 'The PowerShell Guide'
$book | Add-Member -MemberType NoteProperty -Name Author -Value 'Jane Doe'
$book | Add-Member -MemberType NoteProperty -Name Pages -Value 250
Write-Output "Title: $($book.Title)"
Write-Output "Author: $($book.Author)"
Write-Output "Pages: $($book.Pages)"
OutputSuccess
Important Notes
You can add multiple properties one by one using Add-Member.
Once added, you can access the new properties like normal object properties.
If you add a property that already exists, it will not overwrite it unless you use -Force.
Summary
Add-Member lets you add new properties to existing objects.
Use NoteProperty to add simple data fields.
Access added properties with dot notation like $object.PropertyName.