Michael Asgian
Michael Asgian

Reputation: 203

Import-Csv - Member already present issue

I have to combine multiple CSV files into a single one. Each of the CSV has a header. One of the columns header is identical. Ideally, the end file (all_out.csv) has to have a single header.

I run the PowerShell code:

Import-Csv out_1_result.csv,out_2_result.csv,out_3_result.csv,out_4_result.csv,out_5_result.csv,out_6_result.csv,out_7_result.csv,out_8_result.csv,out_9_result.csv,out_10_result.csv,out_11_result.csv,out_12_result.csv,out_13_result.csv,out_14_result.csv,out_15_result.csv,out_16_result.csv,out_17_result.csv,out_18_result.csv,out_19_result.csv,out_20_result.csv,out_21_result.csv,out_22_result.csv,out_23_result.csv,out_24_result.csv,out_25_result.csv,out_26_result.csv,out_27_result.csv,out_28_result.csv |
    Export-Csv all_out.csv -NoType 

and I end up with an error

Import-Csv : The member "URL" is already present.

Is there a way to ignore/fix this?

Upvotes: 13

Views: 36942

Answers (2)

Lai Paulo
Lai Paulo

Reputation: 1

Place -Encoding parameter at the end of the command

Import-Csv -Path $output -Encoding UTF8

Export-csv -NoTypeInformation -Path $output -Encoding UTF8

Upvotes: 0

TessellatingHeckler
TessellatingHeckler

Reputation: 29003

One of the columns header is identical

That means each CSV has two columns header 'URL'? Import-Csv creates objects where each header becomes a property name, e.g. @{Id=10; Url='example.com'} and using the same name again will clash.

There is no way this will work cleanly without you changing the csv files, as there is no way to say "use different column names" and also "skip the header row" just with the Import-Csv cmdlet.

The easiest change I can think of is to drop the header line from each one, e.g.:

$CsvFiles = 'out_1_result.csv','out_2_result.csv','out_3_result.csv','out_4_result.csv','out_5_result.csv','out_6_result.csv','out_7_result.csv','out_8_result.csv','out_9_result.csv','out_10_result.csv','out_11_result.csv','out_12_result.csv','out_13_result.csv','out_14_result.csv','out_15_result.csv','out_16_result.csv','out_17_result.csv','out_18_result.csv','out_19_result.csv','out_20_result.csv','out_21_result.csv','out_22_result.csv','out_23_result.csv','out_24_result.csv','out_25_result.csv','out_26_result.csv','out_27_result.csv','out_28_result.csv'

$NewFileNames = $CsvFiles | ForEach-Object { 

    $NewFileName = $_ + "_noheader.csv"

    Get-Content $_ | Select-Object -Skip 1 | Set-Content $NewFileName -Encoding UTF8

    $NewFileName   # write new name to output stream

}

And then, when they have no header line, import them all and specify the header line as a parameter

Import-Csv -Path $NewFileNames -Header 'Col1', 'Col2', 'Url1', 'Url2' | Export-Csv ...

Upvotes: 16

Related Questions