PowerShell Custom Formatter for Mystery Objects

I needed to create a custom output formatter that would work for any object.  Since I need it to work with any object, that means I won’t know before hand what properties the object has, or which of those properties I want to actually output.  So, I couldn’t use any of the existing PowerShell format cmdlets like format-table, format-list, or format-custom.  Instead, I needed to look at each object, get a list of its properties and their associated value(s), and then loop through those and display them with my custom formatter.  Here’s what I did:

   1:  $propnames = $obj | gm | ?{ $_.MemberType -eq "Property"} | select Name; 
   2:  $propvals = $propnames | %{$obj.($_.Name)}; 
   3:  for($i=0; $i -lt $propnames.Count; $i++) {
   4:    write-custom $propnames[$i].Name $propvals[$i]
   5:    }

Thats it.  The first line gets all the “Property” members of the object ($obj), and puts the “Name” of each property into an array called $propnames.  Line 2 gets the value(s) associated with that property name and puts that result into another array called $propvals.  Then I can pass each name/value pair to my write-custom function, which does the custom output work.

Technorati Tags:

Print | posted on Friday, April 03, 2009 11:33 AM

Feedback

No comments posted yet.

Your comment:





 
 

Copyright © Lance Robinson

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski