Creating New Objects – Oneliner

by Sep 2, 2015

Sometimes you may want to create your own objects to store multiple pieces of information. Here is a pretty dense oneliner that illustrates a quick way of creating new objects:

#requires -Version 3 

$Info = 'Test'
$SomeOtherInfo = 12

New-Object PSObject -Property ([Ordered]@{Location=$Info Remark=$SomeOtherInfo })

When you run this, the result is a new object that contains the two pieces of information, and displays them in the properties Location and Remark. Simply rename the keys in the hash table to rename the object properties to your liking.

 
Location Remark
-------- ------
Test         12
 

Note that [Ordered] was added in PowerShell 3.0 and produces ordered hash tables. You can use the same code on PowerShell 2.0 when you omit [ordered]. Without it, the order of the properties in the new object will be random.

Twitter This Tip! ReTweet this Tip!