Powershell sort PSObject alphabetically

巧了我就是萌 提交于 2020-02-23 06:16:50

问题


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


回答1:


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)
  }


来源:https://stackoverflow.com/questions/44056677/powershell-sort-psobject-alphabetically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!