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

Categories

I am using below code to import and export to CSV. The reason why I am doing an export is because I need all columns in the exported CSV to be enclosed in double quotes. But with below code the double quote is only appearing at the first and last of every line.

Import-Csv c:Emp.csv | Export-Csv c:Emp1.csv -NoTypeInformation -Force

Please note that I have already tried below code (that works but takes longer time if size of CSV is > 200MB):

$inform = Get-Content C:A.csv 
$inform | % { 
  $info = $_.ToString().Replace("|", """|""") 
  $info += """" 
  $var = """" + $info 
  $var | Out-File D:B.csv -Append 
}

Sample input (CSV file):

1|A|Test|ABC,PQR

Sample output (CSV file):

"1"|"A"|"Test"|"ABC,PQR"
See Question&Answers more detail:os

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

1 Answer

Export-Csv already adds double quotes around each field by itself, so all you need to do for that is instruct it to use the correct delimiter:

Import-Csv 'C:path	oinput.csv' -Delimiter '|' |
    Export-Csv 'C:path	ooutput.csv' -Delimiter '|' -NoType

However, Export-Csv adds quotes around all fields indiscriminately, so if you want to selectively add quotes around particular fields you're going to need a custom routine:

$reader = New-Object IO.StreamReader 'C:path	oinput.csv'
$writer = New-Object IO.StreamWriter 'C:path	ooutput.csv'

while ($reader.Peek() -ge 0) {
    $line = $reader.ReadLine().Split('|')
    for ($i=0; $i -lt $line.Count; $i++) {
        if ($line[$i] -like '*,*') {
            $line[$i] = '"{0}"' -f $line[$i]
        }
    }
    $writer.WriteLine(($line -join '|'))
}

$reader.Close(); $reader.Dispose()
$writer.Close(); $writer.Dispose()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...