wp44
wp44

Reputation: 265

Loop Through Subfolders And Combine Text files Within - Output Combined File To a Folder

I have a directory of subfolders. Each one contains text files within it. I am trying to combine the files found in each subfolder.

Example:

SubFolder 1 → a.txt + b.txt + c.txt → SubFolder1Merged.txt
SubFolder 2 → x.txt + y.txt + z.txt → SubFolder2Merged.txt

I have referenced this thread.

This is what I have so far:

$startingDir = "C:\Users\WP\Desktop\TextFiles"

function CombineLogs {
  param([string]$startingDir)

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

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

CombineLogs 'C:\Users\WP\Desktop\CombinedTextFiles'  #output the combined text files here

I get a combined.txt generated in CombinedTextFiles - but not individual files merged. Also the file is empty.

I simply want to loop through each subfolder, merge the text files within each folder, then output to my CombinedTextfiles Folder.

Upvotes: 0

Views: 256

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Recursion can be tricky if you don't know how to handle it. And in this case you don't need to implement recursion yourself anyway. Just let PowerShell do the heavy lifting for you:

$startingDir = 'C:\Users\WP\Desktop\TextFiles'
$combinedDir = 'C:\Users\WP\Desktop\CombinedTextFiles'

Get-ChildItem $startingDir -Recurse | Where-Object {
  $txtfiles = Join-Path $_.FullName '*.txt'
  $_.PSIsContainer -and (Test-Path $txtfiles)
} | ForEach-Object {
  $merged = Join-Path $combinedDir ($_.Name + '_Merged.txt')
  Get-Content $txtfiles | Set-Content $merged
}

Upvotes: 1

JosefZ
JosefZ

Reputation: 30103

function CombineLogs
{
  param([string] $startingDir)

  $outputFile = (Split-Path $startingDir -Leaf) + "COMBINED.txt"

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

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

$outputDir ='C:\Users\WP\Desktop\CombinedTextFiles' # output the combined text files here
CombineLogs "C:\Users\WP\Desktop\TextFiles"

Above code snippet would solve TextFilesCOMBINED.txt and NewCOMBINED.txt however does not solve ABCCOMBINED.txt nor xyzCOMBINED.txt in next scenario:

C:\Users\WP\Desktop\TextFiles\ABC\ABC
C:\Users\WP\Desktop\TextFiles\ABC\xyz\ABC
C:\Users\WP\Desktop\TextFiles\New
C:\Users\WP\Desktop\TextFiles\xyz\ABC

Upvotes: 1

Related Questions