Creating Objects in PowerShell 3.0 (Fast and Easy)

by Nov 23, 2012

In PowerShell 3.0, you can cast a hash table to a PSCustomObject type to easily generate your own objects:

$content = @{

The result is an object:
Name                          FirstName                                                id
----                          ---------                                                --
Weltner                       Tobias                                                  123

The primary advantage of this approach is that you control the order of object properties. With the approach used in PowerShell 2.0, this was not guaranteed:

PS> New-Object PSObject -Property $content

                           id Name                          FirstName
                           -- ----                          ---------
                          123 Weltner                       Tobias

Note that in PowerShell 2.0, conversion to PSCustomObject fails, and you get back a hash table.

Twitter This Tip! ReTweet this Tip!