Avoid Add-Member (Part 1)

by Sep 19, 2022

Often the cmdlet Add-Member is used to create simple objects like this:

$user = New-Object -TypeName psobject |
    Add-Member -MemberType NoteProperty -Name LastName -Value 'Weltner' -PassThru |
    Add-Member -MemberType NoteProperty -Name FirstName -Value 'Tobias' -PassThru |
    Add-Member -MemberType NoteProperty -Name Id -Value 123 -PassThru 


$user

This does work, and the result looks like this:

 
LastName FirstName  Id
-------- ---------  --
Weltner  Tobias    123

However, Add-Member is much too expensive to do simple things like this and is intended to expand objects that you already have. If you want to create simple data objects yourself, the common approach is using a hash table and casting it to [PSCustomObject]:

$user = [PSCustomObject]@{
    LastName  = 'Weltner'
    FirstName = 'Tobias'
    Id        = 123
    }

$user

The result is identical yet much easier to code and process. Add-Member is useful to add sophisticated functionality, i.e. adding methods or adding properties to a pre-existing object without changing its type.

 


Twitter This Tip! ReTweet this Tip!