Format-List: sort properties by name

Viewed 23784

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.

8 Answers

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...

... | Format-List | Out-String -Stream | Sort-Object

...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...

... | Format-List | Out-String -Stream -Width ([Int32]::MaxValue) | Sort-Object

...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 of Format-List—you probably aren't going to care by that point.

By using Select-Object with a calculated property (@{}) and then excluding it (-ExcludeProperty) you can also order the properties as you want. This works even when you don't know what's coming upfront.

@(
    [PSCustomObject]@{
        Color   = 'Green'
        Type    = 'Fruit'
        Name    = 'kiwi'
        Flavour = 'Sweet'
    }
) | Select-Object @{Name = 'Flavour'; Expression = { $_.Flavour } },
@{Name = 'Name'; Expression = { $_.Name } }, * -ExcludeProperty Name, Flavour |
Format-List

Output:

Flavour : Sweet
Name    : kiwi
Color   : Green
Type    : Fruit
Related