Concatenate Files Using PowerShell

Rohan Timalsina May 24, 2022
  1. Use Out-File to Concatenate Files Using PowerShell
  2. Use Set-Content to Concatenate Files Using PowerShell
Concatenate Files Using PowerShell

PowerShell allows you to perform different file operations, such as creating, copying, moving, removing, viewing, and renaming files. Another important feature lets you concatenate multiple files into a single file.

You can easily merge the multiple files’ content into a single file. This tutorial will introduce different methods to concatenate files using PowerShell.

Use Out-File to Concatenate Files Using PowerShell

The Out-File cmdlet sends the output to a file. If the file does not exist, it creates a new file in the specified path.

To concatenate files with Out-File, you will need to use the Get-Content cmdlet to get the content of a file. Normally, Get-Content displays the output in the console.

You have to pipe its output to Out-File, so it sends the output to a specified file. The following example merges two files’ content into a test3.txt.

Get-Content test1.txt, test2.txt | Out-File test3.txt

Run the following command to verify the content of a test3.txt file.

Get-Content test3.txt

Output:

This is a test1 file.
This is a test2 file.

As you can see, the content of both test1.txt and test2.txt are copied to test3.txt. If you want to concatenate all .txt files in the directory, you can use *.txt to select all files.

Get-Content *.txt | Out-File new.txt

Use Set-Content to Concatenate Files Using PowerShell

You can also use Set-Content instead of Out-File. The Set-Content is a string-processing cmdlet in PowerShell.

It writes new content or replaces the content in a file.

Get-Content test1.txt, test2.txt | Set-Content new.txt

Check the content of a new.txt file using Get-Content.

Get-Content new.txt

Output:

This is a test1 file.
This is a test2 file.

In this way, you can easily concatenate multiple files using PowerShell.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell File