0

I'm trying to load several .csv files (with the same columns) into the same array from different directories.

$csv1 = Import-Csv "PATH1"
$csv1 = Import-Csv "PATH2"
$csv1 | Export-Csv C:\test.csv

This just outputs the last .csv loaded, what would be the best way to do this?

8
  • 2
    Hey this should to the trick if i can stop importing the headers of the 2nd .csv file? Commented Apr 27, 2017 at 19:21
  • 1
    found out i could use the += on the 2nd csv file to add it to the array. thanks Commented Apr 27, 2017 at 19:30
  • 1
    @TessellatingHeckler - Get-Content ...| Set-Content ... might "work", except that if it's a CSV in standard format (first line is headers) he'll end up with a record in the middle that duplicates his headers, e.g., Name="Name" Address="Address" etc. His solution using += is better. Commented Apr 27, 2017 at 19:43
  • hey @JeffZeitlin if i wanted to add an additional colum per line stating what path the file came from how would i do this? Commented Apr 27, 2017 at 19:45
  • 2
    @JeffZeitlin No need to make a new object when you could use -PassThru on Add-Member or Select-Object to make a calculated property. @Bunion Here is a one liner that adds that property: ($(Import-Csv "PATH1" | Add-Member -Name "SourcePath" -Value "PATH1" -MemberType NoteProperty -PassThru) + $(Import-Csv "PATH2" | Add-Member -Name "SourcePath" -Value "PATH2" -MemberType NoteProperty -PassThru)) | Export-CSV C:\test.csv Commented Apr 27, 2017 at 21:42

1 Answer 1

2

When in doubt, read the documentation. The Import-Csv cmdlet accepts an array of path strings as input, so all you need to do (assuming that all your CSVs have the same fields) is something like this:

$src = 'C:\path\to\input1.csv', 'C:\path\to\input2.csv', ...
$dst = 'C:\path\to\output.csv'

Import-Csv $src | Export-Csv $dst -NoType

If you want an additional column with the path of the source file you need some additional steps, though:

$src | ForEach-Object {
  $path = $_
  Import-Csv $path | Select-Object *,@{n='Path';e={$path}}
} | Export-Csv $dst -NoType
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.