Select-Object不返回对象?

时间:2014-10-23 21:10:35

标签: powershell powershell-v2.0 powershell-v3.0

以下代码返回预期列表。

$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:\>

2 个答案:

答案 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的表达式。