02 / WORKING WITH DATA · LESSON 08

Make a useful summary

Sort records by a numeric property and choose the top results.

10 min · learn at your pace

Put results in order

Sort-Object orders objects using a property. Add -Descending to put the largest value first:

$items | Sort-Object UsedGB -Descending

Then Select-Object -First 2 takes the first two records. Order matters: sorting before selecting finds the two largest values.

Group and measure

Group-Object gathers records with the same property value and reports a count:

$devices | Group-Object Status

Measure-Object calculates summaries. For objects with a numeric property:

$items | Measure-Object -Property UsedGB -Sum -Average

These commands return objects too. You can inspect the count, sum, or average and use it in another step.

Check your types when sorting imported data. The strings '100' and '20' sort differently from the numbers 100 and 20. Convert a numeric-looking string to [int] when you need numeric comparisons.

Try an example.ps1
$items = @(
    [pscustomobject]@{Name='WEB-01'; UsedGB=30}
    [pscustomobject]@{Name='DB-01'; UsedGB=60}
    [pscustomobject]@{Name='WEB-02'; UsedGB=90}
)
$items | Measure-Object -Property UsedGB -Sum -Average
YOUR TURN

Put it into practice.

Return the two objects with the highest UsedGB values, largest first. Preserve their Name and UsedGB properties.

See an explained solution
One way to solve it.ps1
$items = @(
    [pscustomobject]@{Name='WEB-01'; UsedGB=30}
    [pscustomobject]@{Name='DB-01'; UsedGB=60}
    [pscustomobject]@{Name='WEB-02'; UsedGB=90}
)
$items | Sort-Object UsedGB -Descending | Select-Object -First 2

The order is WEB-02 (90 GB), then DB-01 (60 GB). Selecting after sorting preserves the two complete records.