Posts RSS Comments RSS 249 Posts and 391 Comments till now

blog: Creating Custom Objects with “Select-Object”

Once you grab a hold of the "Object" concept in Powershell it brings a whole new light to scripting. The power that is at your finger tips is basically limitless, but to harness this power you not only need to know how to use objects but also create them as well.

Here is my way of creating objects.
  1. $myobj = ""| select-Object Server,Result
IMO this is the simplest way to create custom objects.

Effectively what happens is you set your $myobj to a empty string and pipe to select-object. While this may seem odd, its actually quite useful because what select-object returns is a PSCustomObject with the properties that you specify. This allows you to create you object with defined properties that you can fill out later in one line.

The "proper" way to create a custom object is to do this.
  1. $myobj = new-object System.Object
  2. $myobj | add-member -membertype noteproperty -name Server -value $sname
  3. $myobj | add-member -membertype noteproperty -name Result -value $sResult
While this isn't that much more work... I think its harder to read (and more typing) so I go with this shortcut
  1. $myobj = "" | select-Object Server,Result
  2. $myobj.Server = $sname
  3. $myobj.Result = $sResult
I will give you one warning about select-object (not related, but while I'm on this subject.) select-object does Change the object type and therefore you lose methods and properties you may expect to be there. I have seen numerous post on the news groups that have this exact problem.

If you pipe Get-ChildItem to Get-member you get tons of methods and properties for both System.IO.FileInfo and System.IO.DirectoryInfo
  1. PS> get-childitem | gm
Now pipe it to select-object and do a Get-Member
  1. PS> (get-childitem | select-object Fullname,length) | gm
  2.  
  3. TypeName: System.Management.Automation.PSCustomObject
  4.  
  5. Name MemberType Definition
  6. ---- ---------- ----------
  7. Equals Method System.Boolean Equals(Object obj)
  8. GetHashCode Method System.Int32 GetHashCode()
  9. GetType Method System.Type GetType()
  10. ToString Method System.String ToString()
  11. FullName NoteProperty System.String FullName=C:WindowsSystem32409
  12. length NoteProperty length=null
Just be careful to remember this. I actually avoid using select-object to filter objects simply because of this. Instead... I just use the properties.

Trackback this post | Feed on Comments to this post

Leave a Reply