PowerShell中的多个条件匹配

作业系统

您好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

PS:您上面提供的代码与所有字段都不匹配,它只是在检查Name参数(不必要地遍历其他参数)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章