In the previous tip we looked at creating simple data objects, and it became evident that instead of using Add-Member, you can cast a hash table to [PSCustomObject].

However, what if you need to add a property to an object at a later time? Well, if you already have a real object and want to expand its members, then Add-Member is again the correct way:

# create a real object:
$user = [PSCustomObject]@{
    LastName  = 'Weltner'
    FirstName = 'Tobias'
    Id        = 123
    }

# at a later time, add one more property:
$user = $user | Add-Member -MemberType NoteProperty -Name Notes -Value 'SomeNotes' -PassThru

$user 

However, if you are just constructing your object yourself, and you would just want to collect the properties step by step within your script, then you can keep your data in an ordered hash table and convert it to a real object at the end:

# create an ordered hash table:
$hash = [Ordered]@{
    LastName  = 'Weltner'
    FirstName = 'Tobias'
    Id        = 123
    }

# at a later time, add one more property:
$hash.Notes = 'SomeNotes'

# only now convert the hash table to a real object
$user = [PSCustomObject]$hash

$user

The end result is the same, and you retain full control over object creation and its members until you cast the ordered hash table to [PSCustomObject]. The same works with a regular hash table except then the properties will appear in random order in your object.




Twitter This Tip! ReTweet this Tip!

Anonymous