Powershell脚本缺少结果属性

时间:2020-06-07 12:41:54

标签: powershell select-object group-object

我不确定脚本出了什么问题。我有一个由Name,Count,Owner组成的3列csv文件。目标是获取每个名称的最高计数,然后输出所有3列,但是Owner列未输出。我只得到Name, Total。如果有人可以帮助我显示问题所在,我将不胜感激。

$total = Import-Csv -Delimiter ',' -Path "file.csv"

$total = $total | Group-object -Property Name | Select Name,  @{ N = 'Total';E = {($_.Group | Measure-Object -Property count -Maximum).Maximum }},Owner

csv文件的内容:

"Name","Count","Owner"
"ctx_Prd-DG","1","User1"
"PRD-Fa","5","User2"
"ING-PROD","3","User2"
"PROD-DG03","0","User2"
"PROD-DG01","0","User2"
"PRD-2018-DG","1","User3"
"PRD-7-DG","5","User3"
"PRD-7-DG-PR15","0","User3"
"PRD-CS-DG","0","User3"
"PRD-INSIGHT-DG","0","User3"
"PRD-LIVE-DG","0","User3"
"DC01-DG","0","User4"
"Test - DG","0","User4"
"PRD-CS-DG","0","User3"
"INSIGHT-DG","0","User3"
"ctx_Prd-DG","1","User1"
"PRD-Fa","1","User2"
"ING-PROD","0","User2"
"PROD-DG03","0","User2"
"PROD-DG01","0","User2"
"PRD-2018-DG","7","User3"
"PRD-7-DG","5","User3"
"PRD-7-DG-PR15","0","User3"
"PRD-CS-DG","0","User3"
"PRD-INSIGHT-DG","0","User3"
"PRD-LIVE-DG","2","User3"
"DC01-DG","1","User4"
"Test - DG","8","User4"
"PRD-CS-DG","20","User3"
"INSIGHT-DG","0","User3"

2 个答案:

答案 0 :(得分:0)

您考虑过此选项吗?

$total = Import-Csv -Path file.csv
$grouped = $total | Group-Object -Property Name
$output = $grouped | Select-Object Name, @{ N = 'Total'; E = {$_.Count} }, @{ N='Owner'; E= {($_.Group).Owner}}

关于“名称,表达式”语法,这是一个有用的问题,张贴在SO中。

Select-Object expression

答案 1 :(得分:0)

$total | Group-Object -Property Name没有属性“所有者”

# `Get-Member -MemberType Properties` shows properties of an object.
$group = $total | Group-Object -Property Name
$group | Get-Member -MemberType Properties

# See how `Group-Object` groups each item,
$group[1].Group
$group[2].Group

所以您的代码将如下所示

$csv =  Import-Csv "file.csv"
$total = $csv | Group-Object -Property Name | Select Name,  @{
  N = 'Total'
  E = { ($_.Group | Measure-Object -Property count -Maximum).Maximum }
}, @{
  N = 'Owner'
  E = { $_.Group.Owner[0] }
}