简体   繁体   English

Powershell 按字母顺序对 PSObject 进行排序

[英]Powershell sort PSObject alphabetically

Given a custom powershell object (bar) that is created from json (foo.json)给定一个从 json (foo.json) 创建的自定义 powershell 对象 (bar)

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.我还尝试将 PSObject 转换为哈希表(哈希表似乎会根据名称自动排序),然后将该哈希表转换回 json,但它再次失去了顺序。

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

Update更新
Changed foo.json to include values aswell as keys更改 foo.json 以包含值和键

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:正如Mathias R. Jessen 所指出的,这里没有要排序的集合,只有一个要排序其属性的对象,因此您需要通过Get-Member进行反射以获取对象的属性:

$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 :使用-pv ( -PipelineVariable ) 来“缓存” 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可以直接从管道发送

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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