Kostas
Kostas

Reputation: 41

Count Files by Name

I am looking for a way to count files from many sub-folders but the tricky part is that i want to filter them by part of their names. To be more specific, all files have a date at the middle of their names. If I want to just count the files within a specific folder I use this:

dir * |%{$_.Name.SubString(7,8)} | group |select name,count|ft -auto 

And works like a charm. The problem lies that it cannot see more than one folder. Also a second problem is that in the result, I want to see the path name of the grouped counts. I am also testing this:

dir -recurse |  ?{ $_.PSIsContainer } | %{ Write-Host $_.FullName (dir $_.FullName | Measure-Object).Count } 

but I cannot implement the date filter from inside the name in this functions. I am also attaching an example of how is the format and how I would like the results.

enter image description here

Any help?

Upvotes: 1

Views: 2550

Answers (1)

Clijsters
Clijsters

Reputation: 4256

I am looking for a way to count files from many sub-folders but the tricky part is that I want to filter them by part of their names. To be more specific, all files have a date at the middle of their names.

It is not 100% clear to me, if you really want to filter them or to group them before counting, so I'll show both.

Assuming that this middle of their names is, e.g., delimited by _ this can be achieved the following way:

# C:/temp/testFolder/myName_123_folder/text.txt
Get-ChildItem * -Recurse |
    Select-Object -Property Name, @{Name = "CustomDate"; Expression = {$_.Name.Split("_")[1]}} |
    #This is how you would _filter_
    #Where-Object {$_.Custom -eq "123"} |
    Group-Object -Property CustomDate |
    Select-Object Name, Count

Don't forget to check if the file name matches this pattern, before splitting. This can be done with a Select-Object statement between gci and 1. select, which checks the file name for your specific pattern.


Your question shows also that you wanted to filter for only directories:

dir -recurse |  ?{ $_.PSIsContainer } | %{ #[...]

Which is not very efficient.

From the Docs of Get-ChildItem:

-Directory

Gets directories (folders).

To get only directories, use the -Directory parameter and omit the -File parameter. To exclude directories, use the -File parameter and omit the -Directory parameter, or use the -Attributes parameter.

This means, the preferred way to search only for Directories is:

Get-ChildItem -Recurse -Directory | % { #[...]

Upvotes: 1

Related Questions