Karl Prosser posts a PowerShell script quick and dirty new custom object as a way to create PowerShell objects on the fly. I’ve come across the need for this and posted an approach PowerShell Function Factory after reading up on Managing Records in Python.
Yet Another Approach To Building Custom Objects
This function peels off two items at a time placing them in $key and $value, $list gets the remainder (it has two fewer items now). Then key/value pair is added to the $Properties hash table. The while loop continues until $list is empty.
After the $Properties hash table is built up, a new PSObject is returned with those properties created and populated by using the –Property parameter on New-Object.
Function New-PSCustomObject ($list) { $Properties = @{} while($list) { $key, $value, $list = $list $Properties.$key = $value } New-Object PSObject -Property $Properties } Function ql {$args} New-PSCustomObject ( ql Name "John Doe" Age 10 Height (6*12) )
Result
Still rolling this around in my head. Love to hear other approaches. Plus, this may show up in PowerShell Version 3.
UPDATE
Thanks to Nivot Ink for a terser approach.
while($key, $value, $list = $list) { $Properties.$key = $value }
{ 5 comments… read them below or add one }
Personally I’ve never been a fan of patterns that rely on a fragile sequence of repeating elements like this. It’s the same reason I’ve always disliked the way the “Filter” property works on common dialogs and I never liked the Switch() function back when I was a VB programmer.
A while back I came up with something like this: http://www.josheinstein.com/blog/index.php/2009/01/clever-use-of-powershell-syntax/
But even that didn’t really satisfy me because it relied on a global function called Field due to the way advanced functions in a module work with scriptblocks passed in as parameters.
What would be *great* is if they would deprecate the existing @{ } Hashtable behavior and replace it with another type that implements IDictionary but respects the order of the elements. Then you could support something like:
New-PSObject @{
Name = 'John Doe'
Age = 10
Height = (6*12)
}
I like it. Took me a minute to work out what q1 does, but once I got over that, I really like this. Maybe not as “clean” as using a dictionary, but a lot simpler.
Here is a good write up of the function ql {$args} Year of the Pig Revisited – the magic of QL
@Josh Yes, this is a quick an dirty approach.
regardless of creating objects with it, the “recursive” algorithm using $head, $head2 , $tail = $tail to break this up is just beautiful..
@karl, agreed this is a great little pattern.