Varun Gupta
Varun Gupta

Reputation: 1457

Merge Files over multiple folders using PowerShell

I have a directory structure as below.

Root_dir

   Sub_dir1

   Sub_dir2

   ....

Here I have multiple sub folders in the Root directory. Now each sub folder contains a message.csv file. I want to append them and create a new csv file.

Upvotes: 0

Views: 2240

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

Assuming that all CSVs have the same columns something like this should work:

$root = 'C:\path\to\Root_dir'
$csv  = 'C:\path\to\output.csv'

Get-ChildItem $root -Filter 'message.csv' -Recurse | % {
  Import-Csv $_.FullName 
} | Export-Csv $csv -NoTypeInformation

To remove duplicates from the output try this instead:

$root = 'C:\path\to\Root_dir'
$csv  = 'C:\path\to\output.csv'

Get-ChildItem $root -Filter 'message.csv' -Recurse | % {
  Import-Csv $_.FullName 
} | ConvertTo-Csv -NoTypeInformation | select -Unique | Out-File $csv

Upvotes: 3

Related Questions