[英]How do I sort an array of objects by one of their property values in Powershell?
For example, I have a variable, which returns the line with several arrays:例如,我有一个变量,它返回带有几个 arrays 的行:
@{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10}
I want to sort this line alphabetically by one of parameters.我想按其中一个参数的字母顺序对这一行进行排序。 In this case - by sourceDSAcn , so result must be like that:
在这种情况下 - 通过sourceDSAcn ,所以结果必须是这样的:
@{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10}
How can I do that?我怎样才能做到这一点?
Your output format suggests two things:您的 output 格式表明两件事:
The objects aren't arrays , but custom objects ( [pscustomobject]
instances).这些对象不是arrays ,而是自定义对象(
[pscustomobject]
实例)。
You've used the Write-Host
cmdet to print these objects to the host (display), which results in the hashtable-literal- like representation shown in your question (see this answer ).您已使用
Write-Host
cmdet 将这些对象打印到主机(显示),这导致在您的问题中显示类似哈希表文字的表示(请参阅此答案)。
Out-Host
cmdlet.Out-Host
cmdlet。Write-Output
cmdlet or, preferably, PowerShell's implicit output feature, as shown below;Write-Output
cmdlet,或者最好使用 PowerShell 的隐式 output 功能,如下所示; for more information, see this answer . In order to sort (custom) objects by a given property , simply pass the name of that property to为了按给定属性对(自定义)对象进行排序,只需将该属性的名称传递给
Sort-Object
's (positionally implied) -Property
parameter, as Mathias R. Jessen helpfully suggests: Sort-Object
的(位置隐含的) -Property
参数,如Mathias R。Jessen有益地建议:
# Using $variable by itself implicitly sends its value through the pipeline.
# It is equivalent to: Write-Output $variable | ...
$variable | Sort-Object sourceDSAcn # same as: ... | Sort-Object -Property sourceDSAcn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.