以下代码返回预期列表。
$groups = ps | group Name
$groups | Sort-Object Name | % {
$g = $_.Group | measure PM -Sum;
New-Object psobject -Property @{ Name2 = $_.Name; Count = $g.Count; Sum = $g.Sum }
}
但是,使用select
创建自定义对象的以下脚本什么都不返回?我读到Select-object
是另一种创建PSObject
的方法吗?
$groups = ps | group Name
$groups | Sort-Object Name | % {
$g = $_.Group | measure PM -Sum;
select -Property @{ Name = 'Name'; expression = { $_.Name }},
@{ Name = 'Count'; expression = { $g.Count }},
@{ Name = 'Sum'; expression = { $g.Sum }}
}
更新 在Powershell 2.0和3.0上测试过它。他们的行为相同。
Windows PowerShell Copyright (C) 2012 Microsoft Corporation. All rights reserved. PS H:\> $groups = ps | group Name PS H:\> PS H:\> $groups | Sort-Object Name | % { >> $g = $_.Group | measure PM -Sum; >> # New-Object psobject -Property @{ Name2 = $_.Name; Count = $g.Count; Sum = $g.Sum } >> select -Property @{ Name = 'Name'; expression = { $_.Name }}, @{ Name = 'Count'; expression = { $g.Count }}, @{ Name = 'Sum'; expression = { $g.Sum }} >> } >> PS H:\>
答案 0 :(得分:2)
select
语句是一个独立的命令,它不接收来自管道的任何输入,因为它位于foreach
块内。您必须将当前管道对象$_
传递给select语句才能执行任何操作:
$groups | Sort-Object Name | % {
$g = $_.Group | measure PM -Sum;
$_ | select -Property @{ Name = 'Name'; expression = { $_.Name }},
@{ Name = 'Count'; expression = { $g.Count }},
@{ Name = 'Sum'; expression = { $g.Sum }}
}
答案 1 :(得分:1)
如果你想使用Select考虑走这条路线:
$groups = ps | group Name
$groups | Sort-Object Name |
select -Property @{ Name = 'Name'; expression = { $_.Name }},
@{ Name = 'Count'; expression = { $_.Group.Count }},
@{ Name = 'Sum'; expression = { $_.Group | measure PM -Sum | Select -Expand Sum }}
我删除了ForEach,并将$ g的创建移动到了Sum的表达式。