Nov
7
Written by:
Don Jones
11/7/2007 1:51 PM
There's basically two ways to create a custom object - say, an object with a "Name" property and a "Status" property:
$obj = new-object pscustom
$obj | Add-Member NoteProperty Name "Value"
$obj | Add-Member NoteProperty Status "Value"
Or:
$obj = "" | select Name,Status
$obj.Name = "Value"
$obj.Status = "Value"
Same net result. Which is better? Well, they both work, so neither is "better." The second one requires a bit less typing; to my mind, the first one is a bit clearer about what's going on. Seeing "New-Object" lets someone else reading your script know what's going on - you're creating a new object. The second one requires you to know that Select-Object, when given a property list, emits a PSCustom object with the specified properties attached as NoteProperty members... so the second one is less immediately-understandable for someone new, perhaps.
But I use both techniques - the first when I'm coding "formally" (like for book samples), and the second when it's just a quickie for some task I need to accomplish.
1 comment(s) so far...
Re: Custom Objects
@Don - There is a third option that I point out in my earlier post - http://www.powershellcommunity.org/Blogs/CommunityBlogs/tabid/55/EntryID/8/Default.aspx. It is more verbose than either of your methods, but it allows you to get closer to the metal without losing any capability. Also, I think the second option is less clear since you do not really know from the code what type of member will be added to the object.
By jbrinkman on
11/14/2007 3:05 PM
|