Format-List: sort properties by name

2020-04-02 09:05发布

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条回答
一夜七次
2楼-- · 2020-04-02 09:48

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
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-04-02 09:49

I feel sure that you can achieve the desired output. I suggest that you experiment with both Sort-Object (or plain Sort) and also Group-Object (plain Group)

My idea is to place the sort, or group before | format-list

Thus $x | sort-object -property xyz | Format-List

查看更多
登录 后发表回答