如何遍历组对象的结果

时间:2019-07-19 16:56:18

标签: grouping powershell-4.0

我爱Group-Object可以做什么,但我不知道如何访问它返回的内容。 我想将唯一的URL列表写入文件(别无其他),然后按最高计数排序。甚至不确定我是否需要-AsHashTable-AsString,无论有没有尝试过。

$urls = @() 
$urls += "http://example.com/test.aspx?a1"
$urls += "http://example.com/test.aspx?b2"
$urls += "http://example.com/test.aspx?c3"
$urls += "http://example.com/test.aspx?a1"
$urls += "http://example.com/test.aspx?b2"
$urls += "http://example.com/test.aspx?a1"
$urls += "http://example.com/test.aspx?a1"

Write-Host "Group & Count"
$urls | Group-Object
#the above is perfect, I just access to the individual fields there 

Write-Host "`n`nSummary:"

$summaryUrls = Group-Object -InputObject $urls  #| Select Name, Count | Format-Table -Auto 
$summaryUrls 

Write-Host "`n`nLoop:"
foreach ($summaryUrl in $summaryUrls) {
    Write-Host "Name=$($summaryUrl.Name) Count=$($summaryUrl.Count)"
    #could build new array here to write to file but loop isn't doing anything 
}

输出:

Group & Count

Count Name                      Group                                                                                                                                       
----- ----                      -----                                                                                                                                       
    4 http://example.com/tes... {http://example.com/test.aspx?a1, http://example.com/test.aspx?a1, http://example.com/test.aspx?a1, http://example.com/test.aspx?a1}        
    2 http://example.com/tes... {http://example.com/test.aspx?b2, http://example.com/test.aspx?b2}                                                                          
    1 http://example.com/tes... {http://example.com/test.aspx?c3}                                                                                                           


Summary:
    1 http://example.com/tes... {http://example.com/test.aspx?a1 http://example.com/test.aspx?b2 http://example.com/test.aspx?c3 http://example.com/test.aspx?a1 http://e...


Loop:
http://example.com/test.aspx?a1 http://example.com/test.aspx?b2 http://example.com/test.aspx?c3 http://example.com/test.aspx?a1 http://example.com/test.aspx?b2 http://exampl
e.com/test.aspx?a1 http://example.com/test.aspx?a1 1

PowerShell版本:5.1.17763.592

1 个答案:

答案 0 :(得分:1)

来自https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/group-object?view=powershell-6

  

-InputObject

     

指定要分组的对象。输入包含对象的变量,或键入获取对象的命令或表达式。

     

使用 InputObject 参数向Group-Object提交对象集合时,Group-Object会收到一个代表该集合的对象。结果,它创建了一个以该对象为其成员的单个组。

     

要对集合中的对象进行分组,请将其通过管道传递到Group-Object

因此,您需要在作业中将版本与管道一起使用:

$summaryUrls = $urls | Group-Object