jOSe
jOSe

Reputation: 707

Multiple Criteria Matching in PowerShell

Hello PowerShell Scriptwriters,

I got an objective to count rows, based on the multiple criteria matching. My PowerShell script can able to fetch me the end result, but it consumes too much time[when the rows are more, the time it consumes becomes even more]. Is there a way to optimism my existing code? I've shared my code for your reference.

$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
}

Upvotes: 2

Views: 624

Answers (1)

Alec  Collier
Alec Collier

Reputation: 1523

You can do this quite simply using the Group option on a Powershell object.

$csvfile = Import-csv "D:\file\filename.csv"
$csvfile | Group Name,"Region Location","Product Cost" | Select Name, Count

This gives output something like the below

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

P.S. the code you provided above is not matching all of the fields, it is simply checking the Name parameter (looping through the other parameters needlessly).

Upvotes: 1

Related Questions