I have this first CSV:
Server,Info server1,item1 server1,item1
and this 2nd CSV:
Server,Info server2,item2 server2,item2
And I am trying to get this output:
Server,Server,Info,Info server1,server2,item1,item2 server1,server2,item1,item2
As you see, the problem is that the headers of the 2 CSV have the same names, which cause a problem if I parse them into objects and loop over keys.
So I am trying to merge them then reordering them as strings, but my mind can't figure how to do it in the last for
loop:
$file1 = Get-Content ".\Powershell test\A.csv"
$file2 = Get-Content ".\Powershell test\B.csv"
$content = for ($i = 0; $i -lt $file1.Length; $i++) {
'{0},{1}' -f $file1[$i].Trim(), $file2[$i].Trim()
}
$content | Out-File ".\Powershell test\merged.csv"
$firstFileParsed = Import-Csv -Path ".\Powershell test\B.csv"
$secondFileParsed = Import-Csv -Path ".\Powershell test\B.csv"
$secondFilePath = ".\Powershell test\B.csv"
$contentOf2ndFile = Get-Content $secondFilePath
$csvColumnNames = (Get-Content '.\Powershell test\B.csv' |
Select-Object -First 1).Split(",")
$newColumns = @()
foreach($header in $csvColumnNames) {
$newColumns += $header
}
$newColumns = $newColumns -join ","
$contentOf2ndFile[0] = $newColumns
$contentOf2ndFile | Out-File ".\Powershell test\temp.csv"
$tempObject = Import-Csv -Path ".\Powershell test\temp.csv"
$tempFile = Get-Content ".\Powershell test\temp.csv"
$array = @()
$tempArr = @()
for ($i = 0; $i -lt $file1.Length; $i++) {
$tempArr1 = $file1[$i] -split ","
$tempArr2 = $tempFile[$i] -split ","
for ($j = 0; $j -lt $tempArr1.Length; $j++) {
$tempArr += $tempArr1[$j] + "," + $tempArr2[$j]
$tempArr
}
$array += $tempArr
}
$array | Out-File '.\Powershell test\merged.csv'
Server1,Info1,Server2,Info2
would be more useful? – henrycarterukCSV
file with duplicate headers is simply not a valideCSV
format. If youImport-Csv
such aCSV
file, you will get a Import-Csv : The member "Server" is already present. – iRonJoin-Object
cmdlet:$File1 | Join $File2
where the columns are merged in an array:{server1, server2} {item1, item2}
. Than you can access your result ($Result = $File1 | Join $File2
) like:$Result[0].Server[1]
` – iRon