Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Set the root directory where your subdirectories are located
- $rootDirectory = "C:\Your Root Directory"
- # Get all text files in subdirectories
- $textFiles = Get-ChildItem -Path $rootDirectory -Recurse -Filter *.txt
- # Create an empty hashtable to store file contents
- $fileContents = @{}
- # Loop through each text file and combine content with the same name
- foreach ($file in $textFiles) {
- $fileName = $file.Name
- $fileContent = Get-Content $file.FullName -Raw
- # If the file name already exists in the hashtable, append content with a newline
- if ($fileContents.ContainsKey($fileName)) {
- $fileContents[$fileName] += "`r`n$fileContent"
- }
- else {
- # If the file name is not in the hashtable, add it with the content
- $fileContents[$fileName] = $fileContent
- }
- }
- # Specify the output directory for the combined files
- $outputDirectory = "C:\Folder for combined files"
- # Create the output directory if it doesn't exist
- if (-not (Test-Path -Path $outputDirectory -PathType Container)) {
- New-Item -Path $outputDirectory -ItemType Directory
- }
- # Loop through the hashtable and write combined content to new files
- foreach ($fileName in $fileContents.Keys) {
- $combinedContent = $fileContents[$fileName]
- $outputPath = Join-Path -Path $outputDirectory -ChildPath $fileName
- $combinedContent | Out-File -FilePath $outputPath
- }
- Write-Host "Files combined and saved to $outputDirectory"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement