Format-List: sort properties by name

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

    This seems to work OK (edited so it accepts pipeline input):

    function Format-SortedList
    {
        param (
            [Parameter(ValueFromPipeline = $true)]
            [Object]$InputObject,
            [Parameter(Mandatory = $false)]
            [Switch]$Descending
        )
    
        process
        {
            $properties = $InputObject | Get-Member -MemberType Properties
    
            if ($Descending) {
                $properties = $properties | Sort-Object -Property Name -Descending
            }
    
            $longestName = 0
            $longestValue = 0
    
            $properties | ForEach-Object {
                if ($_.Name.Length -gt $longestName) {
                    $longestName = $_.Name.Length
                }
    
                if ($InputObject."$($_.Name)".ToString().Length -gt $longestValue) {
                    $longestValue = $InputObject."$($_.Name)".ToString().Length * -1
                }
            }
    
            Write-Host ([Environment]::NewLine)
    
            $properties | ForEach-Object { 
                Write-Host ("{0,$longestName} : {1,$longestValue}" -f $_.Name, $InputObject."$($_.Name)".ToString())
            }
        }
    }
    
    $Host, $MyInvocation | Format-SortedList
    $Host, $MyInvocation | Format-SortedList -Descending
    

提交回复
热议问题