PowerShell Script to Merge Two Files Easily
Get-Content file1.txt, file2.txt | Set-Content merged.txt to merge two files by reading both and writing their combined content into a new file.Examples
How to Think About It
Algorithm
Code
Get-Content file1.txt, file2.txt | Set-Content merged.txt
Write-Output "Files merged into merged.txt"Dry Run
Let's trace merging 'file1.txt' with 'Hello' and 'file2.txt' with 'World' into 'merged.txt'.
Read file1.txt
Content read: ['Hello']
Read file2.txt
Content read: ['World']
Combine contents
Combined content: ['Hello', 'World']
Write to merged.txt
merged.txt now contains: Hello World
| Step | Action | Content |
|---|---|---|
| 1 | Read file1.txt | Hello |
| 2 | Read file2.txt | World |
| 3 | Combine contents | Hello World |
| 4 | Write merged.txt | Hello\nWorld |
Why This Works
Step 1: Reading files
The Get-Content command reads each file line by line and outputs their contents.
Step 2: Combining content
Listing both files separated by a comma in Get-Content merges their lines in order.
Step 3: Writing merged file
The combined output is sent to Set-Content which writes all lines into the new file.
Alternative Approaches
Get-Content file1.txt | Set-Content merged.txt
Get-Content file2.txt | Add-Content merged.txt
Write-Output "Files merged into merged.txt"Get-Content file1.txt | Out-File merged.txt
Get-Content file2.txt | Out-File merged.txt -Append
Write-Output "Files merged into merged.txt"Complexity: O(n) time, O(n) space
Time Complexity
Reading both files line by line and writing combined content takes time proportional to total lines, so O(n).
Space Complexity
The script holds all lines in memory before writing, so space is O(n) where n is total lines.
Which Approach is Fastest?
Using Get-Content with comma-separated files is simplest and efficient; appending methods add overhead but allow incremental writes.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Get-Content with comma | O(n) | O(n) | Simple, all-at-once merging |
| Set-Content + Add-Content | O(n) | O(n) | Stepwise merging, appending |
| Out-File with -Append | O(n) | O(n) | Formatted output, appending |
Get-Content causes errors or incomplete merging.