Format-List: sort properties by name

后端 未结 8 1985
一向
一向 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:32

    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

    0 讨论(0)
  • 2021-01-17 18:45

    AFAIK, Format-List does not provide such an option.

    For your particular example this should work:

    $x | Select-Object A, B | Format-List
    

    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 for Select-Object.

    EDIT:

    Here it is (let's use $host instead of $x):

    $host | Select-Object ([string[]]($host | Get-Member -MemberType Property | %{ $_.Name } | Sort-Object)) | Format-List
    

    Christopher is right, Select-Object is not absolutely needed:

    $host | Format-List ([string[]]($host | Get-Member -MemberType Property | %{ $_.Name } | Sort-Object))
    
    0 讨论(0)
提交回复
热议问题