Grouping Using Custom Criteria

by Jun 7, 2011

Try using Group-Object to group objects by any property:

PS> Get-Process | Group-Object -property Company

You can also submit a script block and calculate the grouping criteria yourself. The next example shows you how to group by file size into three categories:

PS> $criteria = {

    if ($_.Length -lt 1KB) {
        'tiny'
    } elseif ($_.length -lt 1MB) {    
        'average'
    } else { 
        'huge' }
}
PS> dir $env:windir | Group-Object -Property $criteria

Count Name                      Group
----- ----                      -----
   74 tiny                      {AABBCC, addins, AppCompat, AppPatch...}
   27 average                   {bfsvc.exe, bootstat.dat, DPINST.LOG, DtcIns...
    3 huge                      {explorer.exe, Reflector.exe, WindowsUpdate....

 

Twitter This Tip!
ReTweet this Tip!