Avoid Add-Member (Part 3)

by Sep 23, 2022

In the previous tip we looked at a number of clever alternatives to avoid Add-Member when creating your own new objects.

While using hash tables to design new objects (as shown in previous tips) is common place, PowerShell 5 and better comes with a much better approach: classes. They can be complex but if you want to use them to create simple data objects, classes are really easy to use.

This is what you find most often in PowerShell code when scripters try and create their own objects:

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

$user

And this is how you would use a class for the same purpose:

# create a class definition once that clearly defines your
# object type including the data types of your properties:
class MyUser
{
    [string]$FirstName
    
    [string]$LastName
    
    [ValidateRange(0,10000)][uint32]$Id

    # constructor
    # takes the arguments from the user and assigns them to its properties
    # to initialize the object
    Myuser([string]$FirstName, [string]$LastName, [uint32]$Id)
    {
        $this.FirstName = $FirstName
        $this.LastName = $LastName
        $this.Id = $Id
    }
}

# use the class definition to derive one or more objects of this type:
$user = [MyUser]::new('Tobias','Weltner',123)

$user 

It produces the same data object except this time the properties are also clearly typed, and the resulting object now has a distinct data type:

 
PS> $user

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



PS> $user.GetType().FullName
MyUser
 

Defining the class first will add a few more lines to your code but now you have cleanly defined the design of your objects. Creating objects of this type is now a one-liner, and all objects will be guaranteed to have the same members. No chance for typos or inconsistencies.


Twitter This Tip! ReTweet this Tip!