PowerShell中的多准则匹配

PowerShell中的多准则匹配,powershell,csv,Powershell,Csv,大家好,PowerShell编剧 我的目标是根据多个条件匹配来计算行数。我的PowerShell脚本可以获取最终结果,但它消耗的时间太多[当行数更多时,它消耗的时间就更大]。有没有一种方法可以优化我现有的代码?我已经分享了我的代码供你参考 $csvfile = Import-csv "D:\file\filename.csv" $name_unique = $csvfile | ForEach-Object {$_.Name} | Select-Object -Unique $region_un

大家好,PowerShell编剧

我的目标是根据多个条件匹配来计算行数。我的PowerShell脚本可以获取最终结果,但它消耗的时间太多[当行数更多时,它消耗的时间就更大]。有没有一种方法可以优化我现有的代码?我已经分享了我的代码供你参考

$csvfile = Import-csv "D:\file\filename.csv"
$name_unique = $csvfile | ForEach-Object {$_.Name} | Select-Object -Unique
$region_unique = $csvfile | ForEach-Object {$_."Region Location"} | Select-Object -Unique
$cost_unique = $csvfile | ForEach-Object {$_."Product Cost"} | Select-Object -Unique
Write-host "Save Time on Report" $csvfile.Length
foreach($nu in $name_unique)
{
    $inc = 1
    foreach($au in $region_unique)
    {
        foreach($tu in $cost_unique)
        {
            foreach ($mainfile in $csvfile)
            {
                if (($mainfile."Region Location" -eq $au) -and ($mainfile.'Product Cost' -eq $tu) -and ($mainfile.Name -eq $nu))
                {
                    $inc++ #Matching Counter
                }
            }
        }

    }
    $inc #expected to display Row values with the total count.And export the result as csv
}

您只需在Powershell对象上使用Group选项即可完成此操作

$csvfile = Import-csv "D:\file\filename.csv"
$csvfile | Group Name,"Region Location","Product Cost" | Select Name, Count
这将提供如下输出

Name             Count
----             ------
f1, syd, 10      2
f2, syd, 10      1
f3, syd, 20      1
f4, melb, 10     2
f2, syd, 40      1

另外,您上面提供的代码并不匹配所有字段,它只是检查Name参数(不必要地循环其他参数)

我不认为你现有的代码做了你希望它做的事。。它目前只获得与Name列匹配的行数(+1)。Alec,非常感谢您通知我的错误并给出解决方案。是否可以以csv格式导出相同内容?是的,您可以在末尾添加一个|导出csv选项,您昨天已经包括了该选项。非常感谢。。!