quick and dirty new custom object
January 24th, 2010 by KarlI’ve been looking through a bunch of my old scripts (pre 2007) and found an interesting new-pscustomobject. I wouldn’t recommend you use this since now there are better ways in V2, and if you wanted to do anything more its better to use or build a more elegant custom object DSL/DSV that takes into account many aspects. This script was originally a one liner but i split it up to make it more pretty for the blog.
function new-pscustomobject ([string[]] $names , [object[]] $values )
{$obj = 1| select-object $names;
0..($names.length-1) | % { $obj.$($names[$_]) = $values[$_] };$obj
}
and you could use it like
new-pscustomobject -names name, age, height -values "karl", 29, 195
Whats interesting here are a few things.. one using select-object as a quick and dirty way of creating a stub object with properties without values.. the 1 | pipeing is just to get it to run once and create one object… it really could be anything. Another thing is using the 0..(whatever) to create a collection, and then use foreach to iterate over that. Its very “PowerShelleze” but a fair bit slower than a foreach ($x in $y) or a for loop. I think the real “dynamic language” feature this shows up, is address properties of an object dynamically with $obj.$(expression) where expression calculates the name of the property. That feature of powershell comes in handy so often for me, and cuts down many a 200 line C# solution into a one liner.
Posted in Powershell | 1 Comment »

January 24th, 2010 at 10:22 am
[...] 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 [...]