0

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

Rajat Jain
  • 1,339
  • 2
  • 16
  • 29
db100
  • 55
  • 10

1 Answers1

1

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.

Vivek Kumar Singh
  • 3,223
  • 1
  • 14
  • 27
  • Works like a charm. Thanks – db100 Jul 12 '18 at 10:36
  • @db100 - Please consider accepting the answer if it addressed your query. – Vivek Kumar Singh Jul 12 '18 at 10:40
  • 1
    As you are not interested in the content of the Group property you could add `-NoElement` to the `Group-Object` this will avoid some overhead. While this is a question of personal preference I'd insert a line break after the pipe symbols and indent to not have these overlong commands forcing to scroll sideways. Otherwise +1 –  Jul 12 '18 at 13:19