Search code examples
windowspowershelldirectory-structure

Recursively count filtered files in subfolders and group results


I want to count all files with a particular prefix in a directory and then display the results based on each sub directory.

The directory tree is as follows

Test
  January
     sms20180101_110.unl
     rec20180101_110.unl
     data20180101_110.unl
  February
     sms20180201_110.unl
     rec20180201_110.unl
     data20180201_110.unl
  March
    sms20180301_110.unl
    rec20180301_110.unl
    data20180301_110.unl

So, I need to count for example the total data files in each subdirectory and display results as follows

January      1
February     5
March        10   

I wrote the following command in Powershell

Get-ChildItem -Path D:\Test -Filter *data* -Force -Recurse | Measure-Object | %{$_.Count}

So, the problem is it is giving me the total files in the root directory

A similar question was asked here Recursively count files in subfolders but I have not been able to customize the solutions provided here to my need


Solution

  • Based on your scenario, you can use Group-Object like this -

    Get-ChildItem -Path D:\Test -Filter *data* -Force -Recurse | Group-Object -Property Directory | Select-Object Name, Count
    

    This will list all the name of the folders and sub-folders along with the count of files having data in it's name.