Prof. Powershell

Even Better Together

More grouping tricks, this time with the -groupby parameter of the Format-List and Format-Table cmdlets.

Last time I showed you how to use the Group-Object cmdlet to add a little organization to your objects. That cmdlet is great when you want to reuse the grouping information without having to rerun a potentially long running command. But maybe you need a quick report view of something using groups. For that task, use the Format-Table or Format-List cmdlets. Both have a -groupby parameter. Here are some examples. I'll let you try them out to see the results.

First, open a PowerShell prompt and type:

PS C:\> get-process | format-table -groupby Company

The output probably isn't what you were expecting. That's because Format-Table is grouping objects as they are passed to it. If we want all processes from the same company to be listed together they need to be sorted first:

PS C:\> get-process | sort company | format-table -groupby Company

Now you should get the result you were expecting. Here's another one:

PS C:\> dir $env:userprofile\documents | sort extension | Format-table -groupby extension Name,Length,CreationTime,LastWriteTime

This expression will list all files in my Documents folder sorted and grouped by file extension. The report will display the file name, its size, when it was created and when it was last modified. Finally, here's one longer one-liner:

PS C:\> get-wmiobject win32_service -filter "state='running'" | sort StartName | format-list -groupby startname Name,Displayname,Description,PathName | out-file c:\reports\runningsvc.txt

I use the Get-WMIObject cmdlet to retrieve all services that are currently running. The StartName property reflects the service account name which is what I'm after. The sorted service objects are then piped to Format-List which groups them by the StartName property and also selects a subset of properties (Name, DisplayName, Description and PathName). Instead of sending the result to the console, I pipe it to Out-File, which saves the formatted output to a text file.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

Upcoming Training Events

0 AM
Live! 360 Orlando
November 17-22, 2024
TechMentor @ Microsoft HQ
August 11-15, 2025