Advertisement
AInonymous

Untitled

Dec 6th, 2023 (edited)
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. # Set the root directory where your subdirectories are located
  2. $rootDirectory = "C:\Your Root Directory"
  3.  
  4. # Get all text files in subdirectories
  5. $textFiles = Get-ChildItem -Path $rootDirectory -Recurse -Filter *.txt
  6.  
  7. # Create an empty hashtable to store file contents
  8. $fileContents = @{}
  9.  
  10. # Loop through each text file and combine content with the same name
  11. foreach ($file in $textFiles) {
  12. $fileName = $file.Name
  13. $fileContent = Get-Content $file.FullName -Raw
  14.  
  15. # If the file name already exists in the hashtable, append content with a newline
  16. if ($fileContents.ContainsKey($fileName)) {
  17. $fileContents[$fileName] += "`r`n$fileContent"
  18. }
  19. else {
  20. # If the file name is not in the hashtable, add it with the content
  21. $fileContents[$fileName] = $fileContent
  22. }
  23. }
  24.  
  25. # Specify the output directory for the combined files
  26. $outputDirectory = "C:\Folder for combined files"
  27.  
  28. # Create the output directory if it doesn't exist
  29. if (-not (Test-Path -Path $outputDirectory -PathType Container)) {
  30. New-Item -Path $outputDirectory -ItemType Directory
  31. }
  32.  
  33. # Loop through the hashtable and write combined content to new files
  34. foreach ($fileName in $fileContents.Keys) {
  35. $combinedContent = $fileContents[$fileName]
  36. $outputPath = Join-Path -Path $outputDirectory -ChildPath $fileName
  37. $combinedContent | Out-File -FilePath $outputPath
  38. }
  39.  
  40. Write-Host "Files combined and saved to $outputDirectory"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement