≡ Menu

Merging file contents using powershell

Merging file contents is very easy with powershell. If you are familar with two powershell cmdlets(get-content, add-content) you are done with the task.

See the below example, where I have multiple files with same name but in different directories. The below code will search for the files and merges its contents to a new file called “globalmergedfile.txt”.

$allmyfiles = Get-childitem c: -recurse | where {$_.Name -eq “mytest.txt” }
$mergedfile = “c:globalmergedfile.txt”
foreach ($myfile in $allmyfiles) {
$fullpath = $myfile.fullname
$content = Get-content $fullpath
add-content $mergedfile $content
}

So what the above code doing is, searches the c: drive for all the files which has name “mytest.txt” and then enters a for loop where it reads contents of each file and adds it to globalmergedfile.txt.

Hope this code helps you in your scripts.

Comments on this entry are closed.