CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Group-Object cmdlet – To Group Objects

When we display the list of objects using PowerShell commands, the objects will be displayed in specified format; for example, list format. For more readability, it is very useful to group the objects depending on their properties values.

The Group-Object cmdlet

PowerShell provides Group-Object cmdlet to group the objects based on their properties values. As this needs a collection to group the objects, the output of another cmdlet is the input to Group-Object cmdlet. We use this cmdlet with the pipeline.

We use an optional parameter, -Property parameter to specify the properties for grouping. For example, to group the list of files based on their size, below is the command.

PS C:\> Get-ChildItem | Group-Object -Property Length

We will try to group the files based on their extension. How does it possible? Nowhere in the results of Get-ChildItem, we see a parameter related to file extension. This is where you need to understand the object’s members. I have explained this in my previous article “PowerShell – Get-Member cmdlet – Gets the properties and methods of objects“. Please go through it, before proceeding with this article.

Let’s see what are the members of each object of results of Get-ChildItem cmdlet supports by using the below command.

PS C:\> Get-ChildItem | Get-Member

Observe that, the objects support the Extension property. We use this one to group the files or folders based on their extension.

As discussed above, we can use the -Property parameter to specify the properties to the group when using Group-Object cmdlet. We pass Extension as the parameter through -Property parameter to group the files or folder based on their extension. The command looks like below:

PS C:\> Get-ChildItem | Group-Object -Property Extension

And note that, the results were grouped based on the extension.

We will discuss more topics as we go.

[..] David

PowerShell – Group-Object cmdlet – To Group Objects

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top