2020-07-13 14:00:00-05:00

tech development powershell

PowerShell has some functionality that can help in pre-processing data by grouping and aggregating. If you are using ImportExcel this might be useful to pre-aggregate the results prior to an Excel workbook. If you are working with PowerShell and needing to do some quick measurement of objects, maybe this will be useful.

Code

$Companies = @(
    [pscustomobject]@{CompanyName = 'Foo'; UserCount = 5 }
    [pscustomobject]@{CompanyName = 'Foo1'; UserCount = 5 }
    [pscustomobject]@{CompanyName = 'Foo'; UserCount = 2 }
    [pscustomobject]@{CompanyName = 'Foo'; UserCount = 3 }
)

$CalculatedResults = $Companies |  Group-Object CompanyName | ForEach-Object {
    $i = $_
    [int]$totalusers = ($i.Group | Measure-Object -Sum -Property UserCount).Sum

    [pscustomobject]@{
        CompanyName = $i.Name
        TotalUsers  = $totalUsers
    }
}
Write-Host "#####################"
Write-Host "Unaggregated Results"
Write-Host "$($Companies | Format-Table -Autosize -Wrap | Out-String)"
Write-Host "#####################"
Write-Host "`n`n`n`n"
Write-Host "#####################"
Write-Host "Calculated Results"
Write-Host "$($CalculatedResults | Format-Table -AutoSize -Wrap | Out-String)"
Write-Host "#####################"