Creating New Objects (Part 2)

by Dec 13, 2021

Most PowerShell users use hash tables to create objects, and so did we in the previous tip:

$o = [PSCustomObject]@{
    Name = "Tobias"
    Id = 19
    Submission = Get-Date
    Birthday = '1999-02-12 18:33:12' -as [DateTime]



A much better way is to first define a type-safe template class, and whenever you need an object of this type, instantiate one:

class Person  
    [string]$Name = "Tobias"
    [int]$Id = 19
    [DateTime]$Submission = $(Get-Date)
    [DateTime]$Birthday = $('1999-02-12 18:33:12' -as [DateTime])


$p = [Person]::new()

The result is the same except this time, your object instance in $o has a distinct type ([Person]) and can be distinguished from other objects whereas the hash table approach always creates [PSCustomObject].

More importantly, the properties of your new object are now type-safe. When a user later submits data, then PowerShell ensures that it matches the desired data type or else complains. Simple PSCustomObjects in contrast accept any data:

PS> $o.Birthday = "Hello"

PS> $p.Birthday = "Hello"
Exception setting "Birthday": "Cannot convert value "Hello" to type "System.DateTime". Error: "The string was not recognized as a valid DateTime. 
There is an unknown word starting at index 0.""

Twitter This Tip! ReTweet this Tip!