Home > Enterprise >  Output multiple .csv files appending the .csv file name as the source folder name with powershell
Output multiple .csv files appending the .csv file name as the source folder name with powershell

Time:10-29

I have 30 folders. Each folder contains 22 .text files. I am trying to get the filenames and row count of each .text files and output it in a .csv file, appending the name of the .csv file with the name of each subfolder.

The script I made works but it will pull all the .text files from all subfolders and output it in a single .csv file.

Any idea how I can create one .csv file per subfolder ?


$results = Get-ChildItem "C:\Users\testserver\Documents\logfiles\*.txt" -Recurse | % { $_ | select name, @{n="lines";e={get-content $_ | measure-object -line | select -expa lines } } } | Select-Object name, lines

$results | Export-Csv "C:\Users\testserver\Documents\results.csv" -notype

CodePudding user response:

Use the Group-Object cmdlet to process the files grouped by the directory they reside in:

$inDir = 'C:\Users\testserver\Documents\logfiles'
$outDir = 'C:\Users\testserver\Documents'

Get-ChildItem -File -Recurse -Filter *.txt $inDir |
  Group-Object DirectoryName | 
    ForEach-Object {
      $outFile = Join-Path $outDir "results-$(Split-Path -Leaf $_.Name).csv"
      $_.Group |
        Select-Object Name, @{ n="Lines"; e={ (Get-Content $_.FullName | Measure-Object -Line).lines } } |
          Export-Csv -NoTypeInformation $outFile
    }

The above creates output files such as results-foo.csv in $outDir, where foo is the name of a subdirectory containing *.txt files.

Note that the assumption is that no two subdirectories in the target $inDir directory tree have the same name; more work is needed if you need to handle such collisions, such as reflecting the relative paths in the file name, with \ replaced with a substitute char.

  • Related