Introduction
Adding properties to objects lets you store extra information in them. This helps you keep related data together in one place.
$object | Add-Member -MemberType NoteProperty -Name PropertyName -Value PropertyValue
$person = New-Object PSObject
$person | Add-Member -MemberType NoteProperty -Name Age -Value 30
$person$car = [PSCustomObject]@{Make='Toyota'; Model='Camry'}
$car | Add-Member -MemberType NoteProperty -Name Year -Value 2020
$car$obj = New-Object PSObject
$obj | Add-Member -MemberType NoteProperty -Name Color -Value 'Blue'
$obj.Color$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)"
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