PowerShell: How to Combine Multiple Text Files into One File


Often you may want to combine multiple text files into one file using PowerShell.

You can use the following methods to do so:

Method 1: Combine Multiple Specific Text Files into One File

Get-Content file1.txt, file2.txt | Set-Content final_file.txt

This particular example will combine the text files named file1.txt and file2.txt into one text file named final_file.txt.

Note that in this example we combined two text files but you can list out even more text files separated by commas to combine even more files together.

Method 2: Combine All Text Files Matching Pattern into One File

Get-Content *cities.txt | Set-Content all_cities.txt

This particular example will combine all text files in the current directory that end in the pattern cities.txt into one text file named all_cities.txt.

The following example shows how to use this syntax in practice.

Example 1: Combine Multiple Specific Text Files into One File

Suppose that we have the following two text files that we would like to combine into one text file:

  • east_cities.txt
  • west_cities.txt

We can use the Get-Content cmdlet to view the contents of each of these text files:

Each of the text files contain the name of various U.S. cities.

Suppose that we would like to combine these two text files into one file.

We can use the following syntax to do so:

Get-Content east_cities.txt, west_cities.txt | Set-Content all_cities.txt

The following screenshot shows how to use this syntax in practice:

PowerShell combine two text files into one

Notice that we have successfully combined the content from east_cities.txt and west_cities.txt into one text file named all_cities.txt.

Example 2: Combine All Text Files Matching Pattern into One File

Suppose that we would like to combine all text files in the current directory that end in the pattern cities.txt into one text file.

We can first use the ls cmdlet to view all files in the current directory:

We can see that there are four total files in the current directory and two of the files end in the pattern cities.txt.

We can use the following syntax to combine each of the files that end in this specific pattern into one text file:

Get-Content *cities.txt | Set-Content all_cities.txt

The following screenshot shows how to use this syntax in practice:

PowerShell combine all text files with pattern into one file

Notice that we have successfully combined the content from all text files that ended in the pattern cities.txt into one text file named all_cities.txt.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Add Column to CSV
PowerShell: How to Use Export-Csv with No Headers
PowerShell: How to Use Export-Csv and Specify Column Order

Leave a Reply