首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Powershell中按其属性值之一对对象数组进行排序?

问如何在Powershell中按其属性值之一对对象数组进行排序?
EN

Stack Overflow用户
提问于 2020-08-03 19:28:42
回答 1查看 6.1K关注 0票数 3

例如,我有一个变量,它用几个数组返回行:

代码语言:javascript
复制
@{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10}

我想按参数之一按字母顺序排列这一行。在这种情况下- by sourceDSAcn,所以结果必须是这样的:

代码语言:javascript
复制
@{sourceDSAcn=A; LastSyncResult=9} @{sourceDSAcn=B; LastSyncResult=0} @{sourceDSAcn=C; LastSyncResult=0} @{sourceDSAcn=M; Last SyncResult=10}

我怎么能这么做?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-03 22:30:00

您的输出格式说明了两点:

  • 对象不是数组,而是自定义对象([pscustomobject]实例).

您已经使用this answer). cmdet将这些对象打印到主机(显示),从而在您的问题中显示出类似哈希表的类文字表示(请参阅this answer).)。

代码语言:javascript
复制
- If, instead, you want the usual rich display formatting you get by default - while still sending the output to the _host_ only rather than to the _success output stream_ - you can use the [`Out-Host`](https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Core/Out-Host) cmdlet.
- Conversely, to produce _data_ output to the _pipeline_, use either the [`Write-Output`](https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Write-Output) cmdlet or, preferably, PowerShell's implicit output feature, as shown below; for more information, see [this answer](https://stackoverflow.com/a/60534138/45375).

为了按给定属性对(自定义)对象进行排序,只需将该属性的名称传递给

Sort-Object的(位置隐含的) -Property参数,正如Mathias R. Jessen有用的建议:

代码语言:javascript
复制
# 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
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63235776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档