I'm trying to import data from an Excel spreadsheet into a Powershell script and add up the values of one column while sorting the results based on the value of another column. The example below probably illustrates this better than I can in words.
The end goal is to add up the values in the SUBMIT column for each Agent and then export that data to a separate spreadsheet, but I can't figure out the first step of adding the values together and grouping them with the Agent.
foreach ($data in (Import-Excel "C:\prod\actstest.xlsx")) {
$result += $data.Submit
}
Write-Host $result
When I run the block of code above, it successfully adds up the values in the Submit column but doesn't sort it based on Agent. When I run the below code it successfully sorts them by Agent but doesn't add them up. There must be a way to combine these together but I've been unsuccessful in figuring it out to this point.
$testdata = Import-Excel "C:\prod\actstest.xlsx"
ForEach ($Agency in $testdata) {
$AgentID = $Agency.AGENT
$Product = $Agency.EPROD
$Submit = $Agency.SUBMIT
[int]$SubNum = [convert]::ToInt32($Submit, 10)
ForEach($AgentID in $Agency) {
If ($Product -eq "HOP") {
$Agency | Group-Object AGENT | %{
New-Object psobject -Property @{
Agent = $_.Name
Sum = ($_.Group | Measure-Object -property SUBMIT -Sum).Sum
}
}
}
}
}
This is what I'm getting:
Sum Agent
--- -----
2 05007
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05008
1 05018
1 05018
1 05018
1 05018
1 05018
This is what I'm trying to get:
Sum Agent
--- -----
2 05007
13 05008
5 05018