While most PowerShell users still use hash tables to create new objects, our previous tips have shown that classes aren’t hard to use and provide a range of advantages. Objects created by hash table conversion aren’t type safe, and you can only define properties. If you want to add methods to your object, you need to individually add them using Add-Member.
Here is what most people do:
$o = [PSCustomObject]@{ Name = "Tobias" Id = 19 Submission = Get-Date Birthday = '1999-02-12 18:33:12' -as [DateTime] } | Add-Member -MemberType ScriptMethod -Name GetAgeInDays -Value { (New-Timespan -Start $this.Birthday).TotalDays } -PassThru | Add-Member -MemberType ScriptMethod -Name GetBirthDay -Value { Get-Date -Date $this.Birthday -Format dddd } -PassThru
By separating the object design with a class, you can do all of this in a much cleaner way. Here is the class:
class Person { [string]$Name = "Tobias" [int]$Id = 19 [DateTime]$Submission = $(Get-Date) [DateTime]$Birthday = $('1999-02-12 18:33:12' -as [DateTime]) # add parameterless default constructor Person() {} # add custom constructor that takes parameters Person([string]$Name, [datetime]$Birthday, [int]$Id) { $this.Name = $Name $this.Birthday = $Birthday $this.Id = $id } # add methods [double]GetAgeInDays() { return (New-Timespan -Start $this.Birthday).TotalDays } [string]GetBirthDay() { return Get-Date -Date $this.Birthday -Format dddd } }
The class first defines the type-safe properties. Next, you can optionally define constructors (see previous tip) to help initialize the object with the appropriate information. And finally, you can add all the methods you want. Using the class is now a snap:
PS> [Person]::new OverloadDefinitions ------------------- Person new() Person new(string Name, datetime Birthday, int Id) PS> $p = [Person]::new('Fred','2001-02-16', 456) PS> $p Name Id Submission Birthday ---- -- ---------- -------- Fred 456 26.10.2021 12:34:37 16.02.2001 00:00:00 PS> $p.GetAgeInDays() 7557,52413125172 PS> $p.GetBirthDay() Friday