posts - 598 , comments - 849 , trackbacks - 247

My Links

News

qrcode

Lance Robinson

Create Your Badge

Lance Robinson is a software engineer in Durham, Chapel Hill, Raleigh, and surrounding areas. More about Lance.

 Subscribe

Tag Cloud

Archives

Post Categories

Image Galleries

Blogs

Miscellanous

Noteworthy Stuff

Popular Posts

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 3, 2009 11:33 AM | Filed Under [ PowerShell ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: