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.
If you are dealing with a small number of properties, you can specify their order with the -Property parameter.
Here is an example:
If you have a lot of properties, I am not sure there is any easy way to sort them in Format-List, like Roman said.
The closest I can think of is to create a new psobject based off the old one but with the properties sorted e.g.:
You could get fancier and give the new psobject a typename that matches the old one, etc.
Expanding on Christopher's idea, using
get-member
andformat-list -Property
:This seems to work OK (edited so it accepts pipeline input):
AFAIK,
Format-List
does not provide such an option.For your particular example this should work:
If the property set is not fixed/known then the procedure will be more tricky with use of
Get-Member
and some preprocessing making sorted parameter array forSelect-Object
.EDIT:
Here it is (let's use $host instead of $x):
Christopher is right,
Select-Object
is not absolutely needed:Nothing wrong with the accepted answer, but a really quick-and-dirty option for a one-off—that doesn't require having the collection already in a variable—might be...
...which does a sort on each line of the output of
Format-List
.Note that any property values that go onto the next line will be broken (and probably appear at the top of the output), but this could be fixed by the slightly-less-memorable...
...at the expense of column indentation.
Of course, all object/pipeline info is lost by that
Out-String
call, although—considering the same is true ofFormat-List
—you probably aren't going to care by that point.