Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

powershell - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...