Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format-List: sort properties by name

Is it possible to sort the output of the Format-List cmdlet by property name?
Suppose that I have an object $x with two properties "A" and "B", and when I run Format-List with it I get

(PS) > $x | Format-List
B : value b
A : value a

I would like to have

(PS) > $x | Format-List 
A : value a
B : value b

NOTE: I should have specified from the beginning that, unlike in the example with "A" and "B" properties, the real object I have to deal with has quite a lot of properties, and new ones could be added in the future, so I don't know all the property names in advance.

like image 530
Paolo Tedesco Avatar asked Jul 19 '10 14:07

Paolo Tedesco


1 Answers

The closest I can think of is to create a new psobject based off the old one but with the properties sorted e.g.:

$x | %{$obj = new-object psobject; `
       $_.psobject.properties | Sort Name | `
           %{Add-Member -Inp $obj NoteProperty $_.Name $_.Value}; $obj} | fl

You could get fancier and give the new psobject a typename that matches the old one, etc.

like image 85
Keith Hill Avatar answered Sep 28 '22 08:09

Keith Hill