3
votes

I have around 30 directories with .log files in them. I want to go into each folder and combine the text of all the files in the sub-directories separately. I do not want to combine the text of all the files in all the sub-directories.

Example

I have a directory called Machines

in Machines\ I have

Machine2\
Machine3\
Machine4\

Within each Machine* folder, I have :

1.log
2.log
3.log
etc..

I want to create a script that will do:

First: Go into the directory Machine2 and combine the text of all text files in that directory Second: Go into the Machine3 directory and combine the text of all text file in that directory.

I can use the below if only had one folder, but I need it to loop through several sub folders so I do not have to enter the sub-directory in the command below.

Get-ChildItem -path "W:\Machines\Machine2" -recurse |?{ ! $_.PSIsContainer } |?{($_.name).contains(".log")} | %{ Out-File -filepath c:\machine1.txt -inputobject (get-content $_.fullname) -Append}
1

1 Answers

3
votes

I think a recursive solution would work well. Given a directory, grab the content of all *.log files and dump into COMBINED.txt. Then pull the names of all subdirectories, and repeat for each.

function CombineLogs
{
   param([string] $startingDir)

   dir $startingDir -Filter *.log | Get-Content | Out-File (Join-Path $startingDir COMBINED.txt)

   dir $startingDir |?{ $_.PsIsContainer } |%{ CombineLogs $_.FullName }
}

CombineLogs 'c:\logs'