Loop Through Subfolders And Combine Text files Wit

2019-09-03 22:03发布

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.

2条回答
爷的心禁止访问
2楼-- · 2019-09-03 22:58

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
}
查看更多
太酷不给撩
3楼-- · 2019-09-03 23:01
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
查看更多
登录 后发表回答