Home > Software engineering >  For each Sub Directory write a separate file (csv) with information
For each Sub Directory write a separate file (csv) with information

Time:01-05

I have a situation where I need to write an Output file for each folder with data/information within each folder.

Folder/directory structure:

C:\Logs\15Sec\Ref.Data\Month\Log.Jan\Day.1\
~\Month\~ have folders up to Log.Dec
~\Log.Jan\~ has a folder for 30/31 Days in a month
~\Day.1\~ has files with data  

What I could achieve:

I can read data using a script for all Days in a month and can write the info in a CSV file. thanks to @zett42.

This works fine at the given folder/directory structure -

C:\Logs\15Sec\Ref.Data\Month\Log.Jan\

Script:

$targDir = "C:\Logs\15Sec\Ref.Data\Month\";
$subDir = $(Get-ChildItem "$targDir" –Directory );
foreach($sub in $subDir) {
    Get-ChildItem -Path $sub –Recurse *.log | 
    Select-Object -Property @(
        'FullName'
         @{ Name = "LineCount"; Expression = { 
             (Get-Content -Path $_.FullName | Select-Object -Skip 8 | Measure-Object).Count
         }} 
    ) |
    Export-Csv C:\test\output.csv -NoTypeInformation
}

Problem:

When trying to run the script at a higher folder/directory structure, which is

C:\Logs\15Sec\Ref.Data\Month\

The script only writes the Output file for the last folder present in Month for example Log.May. All other folders (Log.Jan, Log.Feb, etc) information will not be written. I don't know how to do this and couldn't trace the correct help on the internet.

Expectation: A separate file for each Month with the name of the month (Log.Jan.csv, Log.Feb.csv) itself.

CodePudding user response:

Your script currently writes the output for every month, but also overwrites it on every loop iteration - that's why you only see data from the last month. So you just need to update the output path to grab the name from the current month's directory.

Change the export definition to:

Export-Csv "C:\test\$($sub.Name).csv" -NoTypeInformation
  • Related