Format-List: sort properties by name

后端 未结 8 2060
一向
一向 2021-01-17 18:02

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

8条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 18:23

    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
    

提交回复
热议问题