Combining Files in PowerShell

If you need to combine text files in cmd.exe, you would issue the following command:

copy file1.txt+file2.txt+file3.txt combined_files.txt

If you wish to do the same for binary files, you would use the following command:

copy /b file1.bin+file2.bin+file3.bin combined_files.bin

To do the same in PowerShell is pretty straightforward.  If the destination file does not already exist or already contains content, you’ll want to issue the New-Item command first.  If you know it doesn’t exist or is empty, you can skip that line, below.

New-Item -ItemType file ".\combined_files.txt" –force

Get-Content .\file?.txt | Add-Content .\combined_files.txt

Thanks to Gerardo Lopez for his “Combine or Join Two Text Files Using PowerShell” article, which is the basis for this information.


Comments (7)

  1. Michael Banda says:

    I'd suggest another algorythm for BIG files. I tried your version for 30 files with a sum of 1,6 GB data and ran into a RAM limitation.

    New-Item -ItemType file ".combined_files.txt" –force

    Get-ChildItem -filter "file?.txt" | %{ Get-Content $_ | Add-Content .combined_files.txt }

  2. Davor Josipovic says:

    @Michael Banda

    This is good. But is very slow. Get-Content reads “one” line at a time by default. Depending on the sizes of the source files and your available memory it is better (and much faster) to use the “-ReadCount 0” switch to read the whole file into memory, and then send in through the pipe line. So your command becomes:

    Get-ChildItem -filter "file?.txt" | % { Get-Content $_ -ReadCount 0 | Add-Content .combined_files.txt }

  3. Thanks to both of you for the feedback!

  4. Nick Meisher says:

    None of your items worked for me. This is what actually worked since I just used it:

    Get-ChildItem -recurse -include "*.txt" | % { Get-Content $_ -ReadCount 0 | Add-Content .combined_files.txt }

  5. Lourdes Montenegro says:

    Hi Robert,
    Just found this very useful post. Any advice on how to exclude the header row for all files except the first?

  6. Jacopo Ricare says:

    I know this is an old post, but why not use a redirection and have it on one line?

    Get-Content file?.txt > combined_files.txt

    or use the “cat” alias and you can run it in both Powershell (with less typing) and Bash:

    cat file?.txt > combined_files.txt

    1. Jacopo Ricare says:

      Sorry, with a filtering it’s like this:

      ls “file?.txt” | cat > combined_files.txt

      The command above always replace the combined_files.txt. If you wish to append then just replace > with >>.

      ls “file?.txt” | cat >> combined_files.txt

Skip to main content