Recursively read UNC path and count line for specific file

Here is a script that will count the number of lines in each FooBar.csv file it find in all subdirectories.

I want to also show the parent folder for each FooBar.csv file.


# Script to count the lines in each FooBar.csv file, so determining the total open orders each day.

$outFile = “FooBarCount.csv”

If (Test-Path $outFile) {
    Del $outFile

echo ‘Directory,LineCount’ > $outFile

$List = Get-ChildItem -path “\\<servername>\d$\Archive\Main” -Recurse -Include FooBar.csv
foreach ($file in $List)
 $result = Get-Content $file | Measure-Object -Line | Select-Object -ExpandProperty Lines;

    $directory = Split-Path $file.fullname -Parent #get the directory full name
    $parent = Split-Path $directory -Leaf # get the last directory folder name

    $printline = $parent + ‘,’ + $result

    echo $printline
    echo $printline >> $outFile

Leave a Reply