Creating Strongly-Typed Objects (the Easy Way)

Listen to this blog post!

Table of contents:

Most PowerShell scripters use techniques like this to create structured objects:

[PSCustomObject]@{
    Id = 12
    Name = $env:username
    Date = Get-Date
    Remark = 'Some text'
} 

This works, and the result is indeed an object:

Id Name  Date                Remark   
-- ----  ----                ------   
12 tobia 04.07.2025 19:19:38 Some text

Caveats with PSCustomObjects

However, all objects are of the same type: PSCustomObject.

PS> $obj.GetType().FullName
System.Management.Automation.PSCustomObject

Worse, the resulting objects are not strongly typed—their properties can be overwritten with any type of data:

PS> $obj.Id
12

PS> $obj.Id = "accepts strings as well"

PS> $obj.Id 
accepts strings as well

While this can be tolerated in many cases, there is a simple trick to create “real” objects with unique type names and strongly-typed properties:

Creating Better Objects

All you need to do is define a simple class—it serves as a prototype for your objects. Within it, you can specify the data types you want to use for your properties.

# define a class prototype for your object, and
# make sure property names match your hash table keys
class MyUserData
{
    [int]$Id 
    [string]$Name
    [DateTime]$Date
    [string]$Remark
}

That’s it. With your new class defined, you can continue creating objects as before—simply replace the generic [PSCustomObject] with your new unique type name:

# continue creating objects as you have in the past
# but replace [PSCustomObject] with your new class name

$obj = [MyUserData]@{
    Id = 12
    Name = $env:username
    Date = Get-Date
    Remark = 'Some text'
} 

Your objects are now of unique type:

PS C:\> $obj.GetType().FullName
MyUserData

Your properties are now strongly typed and automatically protected from incorrect data types:

PS C:\> $obj.Id = 'can only store integers, text wont work'
Exception setting "Id": "Cannot convert value "can only store integers, text wont work" to type "System.Int32". Error: "Input 
string was not in a correct format."" 

Related links