简体   繁体   中英

Powershell sort PSObject alphabetically

Given a custom powershell object (bar) that is created from json (foo.json)

How would you sort the object alphabetically by key?

foo.json
{
  "bbb": {"zebras": "fast"},
  "ccc": {},
  "aaa": {"apples": "good"}
}

Desired output

foo.json
{
  "aaa": {"apples": "good"},
  "bbb": {"zebras": "fast"},
  "ccc": {}
}

Example

$bar = get-content -raw foo.json | ConvertFrom-Json  
$bar.gettype()  

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    PSCustomObject                           System.Object

I've tried the following using sort-object

$bar = $bar | Sort
$bar = $bar | Sort-Object
Sort-Object -InputObject $bar
Sort-Object -InputObject $bar -Property Name
Sort-Object -InputObject $bar -Property @{Expression="Name"}
Sort-Object -InputObject $bar -Property @{Expression={$_.PSObject.Properties.Name}}

I've also tried converting the PSObject to a hashtable (hashtables appear to automatically sort based on name), then convert that hashtable back to json, but it looses the order again.

$buzz = @{}
$bar.psobject.properties |Foreach { $buzz[$_.Name] = $_.Value }
ConvertTo-Json $buzz -Depth 9

Update
Changed foo.json to include values aswell as keys

As Mathias R. Jessen notes, there is no collection to sort here, just a single object whose properties you want to sort, so you need reflection via Get-Member to obtain the object's properties:

$bar = get-content -raw foo.json | ConvertFrom-Json

# Build an ordered hashtable of the property-value pairs.
$sortedProps = [ordered] @{}
Get-Member -Type  NoteProperty -InputObject $bar | Sort-Object Name |
  % { $sortedProps[$_.Name] = $bar.$($_.Name) }

# Create a new object that receives the sorted properties.
$barWithSortedProperties = New-Object PSCustomObject
Add-Member -InputObject $barWithSortedProperties -NotePropertyMembers $sortedProps

A more streamlined version that uses -pv ( -PipelineVariable ) to "cache" the unsorted custom object produced by ConvertFrom-Json :

$barSortedProps = New-Object PSCustomObject
Get-Content -Raw foo.json | ConvertFrom-Json -pv jo |
  Get-Member -Type  NoteProperty | Sort-Object Name | % { 
    Add-Member -InputObject $barSortedProps -Type NoteProperty `
               -Name $_.Name -Value $jo.$($_.Name)
  }

what about this:

Function Sort-PSObject {
        [CmdletBinding()]
        Param(
            [Parameter(ValueFromPipeline=$true)]$inputString
        )
        process {
            ($inputString | out-string).trim() -split "`r`n" | sort
        }
}

Can send direct from pipeline

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM