Creating New Objects – Alternative

by Jun 14, 2013

There are many ways in PowerShell to create new objects. One of the more advanced approaches uses a hash table to determine object properties and their values:

$content = @{
    User = $env:Username
    OS = (Get-WmiObject Win32_OperatingSystem).Caption
    BIOS = (Get-WmiObject Win32_BIOS).Version
    ID = 12
}

$object = New-Object -TypeName PSObject -Property $content

$object

The result looks similar to this:

As you may note, the order of columns isn't the order you specified in your hash table, though. That's because hash tables are unordered by default. In PowerShell 2.0, to order columns, you would have to post-process your object with Select-Object like this:

In PowerShell 3.0, you can use this alternative:

$content = [Ordered]@{
    User = $env:Username
    OS = (Get-WmiObject Win32_OperatingSystem).Caption
    BIOS = (Get-WmiObject Win32_BIOS).Version
    ID = 12
}

This creates an ordered hash table which preserves the order of columns. Note however that once you use this technique, your code is no longer compatible with PowerShell 2.0.

Twitter This Tip! ReTweet this Tip!