简体   繁体   中英

Powershell. Combine text files in folders across multiple directories

I have tried to do my research, but I can't fathom this one out. I can combine multiple.txt files in a folder. no problem: dir C:\Users\XXXX\AC1\22JUN *.txt | get-content | out-file C:\Users\XXXX\22JUN\AC1_22JUN.txt dir C:\Users\XXXX\AC1\22JUN *.txt | get-content | out-file C:\Users\XXXX\22JUN\AC1_22JUN.txt

however, I have 14 Directories each with subdirectories. (months of the year), and this will only ever grow. How can I write it so that it will go into each directory AC1 - AC14 and then look into each folder JAN-DEC and in each subdirectory create a combined file for AC1_22JUN, AC2_22JUN AC1_22JUL, AC2_22JUL and so on and so on?

is there also a way to rename the output file with data, such as the number of.txt files that have been combined. ie AC1_22JUN_314.txt

many thanks in advance

What you need to do is iterate over all your directories and their subdirectories and run a particular command in each of them. This is easy enough to achieve using the cmdlet Get-ChildItem and a pair of nested foreach loops.

In addition, you need to count the number of text files you've processed so that you can name your aggregate file appropriately. To do this you can break your pipeline using the temporary variable $files . You can later begin a new pipeline with this variable and use its count property to name the aggregate file.

The code for this is as follows:

$dirs = Get-ChildItem -Directory
foreach ($dir in $dirs)
{
    $subdirs = Get-ChildItem $dir -Directory
    foreach ($subdir in $subdirs)
    {
        $files = Get-ChildItem *.txt -Path $subdir
        $name = "$($dir.name)_$($subdir.name)_$($files.count).txt"
        $files | Get-Content | Out-File "$subdir/$name"
    }
}

A few things to note:

  • The script needs to be run from the containing folder - in your case the parent folder for AC1-AC14. To run it from elsewhere you will have to change the first statement into something like $dirs = Get-ChildItem C:\path\to\container -Directory

  • Get-ChildItem is the same as the command dir . dir is an alias for Get-ChildItem . This is NOT the same as the variable $dir which I've used in the script.

  • Running the script multiple times will include any and all of your old aggregate files. This is because the output file is also a.txt file which is caught in your wildcard search, Consider refining the search criteria for Get-ChildItem. or save the output elsewhere

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM