PowerShell中的多个条件匹配

时间:2017-08-08 03:05:43

标签: powershell csv

Hello PowerShell Scriptwriters,

我有一个基于多个标准匹配来计算行数的目标。我的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
}

1 个答案:

答案 0 :(得分:1)

您可以使用Powershell对象上的“组”选项完成此操作。

$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

P.S。您上面提供的代码不匹配所有字段,只需检查Name参数(不必要地循环其他参数)。

相关问题