Search code examples
powershellpowershell-3.0powershell-cmdlet

Powershell Script to count .txt files only in a directory


My goal is to send email to some users to notify about the current count of the files inside some folder directories.

I need to count files only with .txt extensions and exclude folders and files inside this.

please see below illustration

U:\TESTING\Main Folder

Testing Main Folder Image

U:\TESTING\Main Folder\Sub Folder 1

Testing Sub Folder 1 Image

U:\TESTING\Main Folder\Sub Folder 2

Testing Sub Folder 2 Image

output result should look somehting like this

Example output table

Main Folder row should be 1 only, but it also includes the sub folders 1 and 2 and the txt files inside those.

Here's the part of the code that counts the total files

$total = Get-ChildItem $path -Recurse -File -Include *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}

When I remove -Recurse in this line, the result becomes 0 for total column

 $total = Get-ChildItem $path  -File -Include *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}

Solution

  • I found the following workaround

    1. by using -filter instead of -include

    just remove the -recurse to exclude subdirectories files in counting and use -filter instead of -include

    $path = "D:\LIVE"
    
     $total = Get-ChildItem $path  -File -filter *.txt |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}
    
    1. using get-Item instead of Get-ChildItem with -include

    -Filter is limited to using one paramter, so if you want to use -include to use as many searching parameter as you can, use Get-Item instead of get-childItem

    just add * (when no path is declared) or * appending to the existing path

    $path = "D:\LIVE\*"
    
     $total = Get-Item $path -include *.txt, *.xml  |Where-Object {$_.LastWriteTime} | Measure-Object | ForEach-Object{$_.Count}