Home > PowerShell > Merging file contents using powershell

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.

No related content found.

Categories: PowerShell Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>