Creating New Objects (Part 1)

by Dec 9, 2021

In PowerShell, you can use hash tables to create ad-hoc objects:

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

}

$o

Each hash table key turns into a property, and each value turns into the property value. Very simple.

If you need to add methods (commands) to your object, add them via Add-Member:

$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

$o 

Now, your object contains data plus methods to work with the data. For example, you can find out how old the person is (in days), or what the weekday name was when the person was born:

 
PS> $o.GetAgeInDays()
8291,7357887859

PS> $o.GetBirthDay()
Friday 
 

Even if you change object data like the “Birthday” property, the methods still work because they always refer to the current object ($this) and calculate results the moment you run them:

 
PS> $o.Birthday = '2020-01-01'

PS> $o.GetAgeInDays()
664,509873798017

PS> $o.GetBirthDay()
Wednesday 
 

However, using hash tables and Add-Member creates manually defined unique objects. In our next tip we show how to create object with class(es).


Twitter This Tip! ReTweet this Tip!