Using the Group-Object Cmdlet
Arranging Data Into Groups
The Group-Object cmdlet is very cool: it enables you to easily group data by a specified property, then quickly determine how many items are in the resulting categories. For example, this command uses the Get-Service cmdlet to retrieve information about the services installed on a computer, then groups the returned data by status:
Get-Service | Group-Object status
What does that mean? Like they say, a picture’s worth a thousand words:
Count Name Group
----- ---- -----
56 Running {AdobeActiveFileMonitor4.0, ALG, ASChannel, ...
42 Stopped {Alerter, AppMgmt, aspnet_state, Browser...}
This command groups the files in the C:\Scripts folder by file extension:
Get-ChildItem c:\scripts | Group-Object extension
Here’s the kind of information you can expect that command to return:
Count Name Group
----- ---- -----
1 {200}
2 .gif {38DF6AB1-13D4-409C-966D-CBE61F040027.gif, d...
5 .xls {5-15-06.xls, 5-17-06.xls, Book1.xls, invent...
15 .txt {alias.txt, ExcelData.txt, help.txt, methods...
3 .msh {a_new_file.msh, b_new_file.msh, c_new_file....
6 .zip {calculatorv11.zip, IronPython-1.0-Beta2.zip...
4 .log {Employees.log, Employees_NODUPL.log, mylog....
3 .doc {ey.doc, ou.doc, test.txt.doc}
4 .xml {files.xml, my_history.xml, Saved_history.xm...
1 .txtcls {help.txtcls}
8 .vbs {hidden.vbs, imapi.vbs, imapi2.vbs, methods....
1 .wma {HoneyPie.wma}
2 .htm {msh.htm, test.htm}
1 .csv {test.csv}
1 .ps1 {test.ps1}
2 .psc1 {test.psc1, test.psc1e.psc1}
1 .jpg {welder-small.jpg}
And, sure, we can sort that information by the number of files in each group:
Get-ChildItem c:\scripts | Group-Object extension | Sort-Object count
Just pipe the results to Sort-Object, and sort on the Count property. Here’s what you’ll get back:
Count Name Group
----- ---- -----
1 .csv {test.csv}
1 .ps1 {test.ps1}
1 .wma {HoneyPie.wma}
1 .txtcls {help.txtcls}
1 .jpg {welder-small.jpg}
1 {200}
2 .htm {msh.htm, test.htm}
2 .gif {38DF6AB1-13D4-409C-966D-CBE61F040027.gif, d...
2 .psc1 {test.psc1, test.psc1e.psc1}
3 .msh {a_new_file.msh, b_new_file.msh, c_new_file....
3 .doc {ey.doc, ou.doc, test.txt.doc}
4 .log {Employees.log, Employees_NODUPL.log, mylog....
4 .xml {files.xml, my_history.xml, Saved_history.xm...
5 .xls {5-15-06.xls, 5-17-06.xls, Book1.xls, invent...
6 .zip {calculatorv11.zip, IronPython-1.0-Beta2.zip...
8 .vbs {hidden.vbs, imapi.vbs, imapi2.vbs, methods....
15 .txt {alias.txt, ExcelData.txt, help.txt, methods...
Group-Object Aliases |
---|
|