I am processing a .txt file, which needs to be repeated every 10 lines. I then want to turn this into a .csv file. However, some of the .txt file contains commas which I want to keep in a single cell in the resulting .csv file. I think my approach to exporting using StreamWriter may be a limiting factor here, how can I refactor this code so that the resulting csv ignores commas within values?
$input = "<file path>"
$output = "<file path>"
$fileContents = Get-Content -Path $input
$writeToOutput = $true
if($writeToOutput){
$sw = New-Object System.IO.StreamWriter $output
$sw.WriteLine("Header1,Header2,...,HeaderN")
}
$ReadCount = 10
Get-Content -Path $input -ReadCount $readCount | ForEach-Object {
$serviceNameStr = $_[0].ToString()
$serviceName = $serviceNameStr.Substring($serviceNameStr.IndexOf(": ")+2)
$descStr = $_[1].ToString()
$desc= $descStr.Substring($descStr.IndexOf(": ")+2)
# $desc = "this is used for a, b, and c"
#... the remaining 8 lines to read/process
if($writeToOutput){
$sw.WriteLine("$serviceName,$desc,...,$lastVar")
# $desc will not be contained to a single cell but rather "this is used for a" | " b" | " and c"
}
}
if($writeToOutput){
$sw.Close()
}
If I need to use Export-Csv to ignore the commas, how do I translate what I'm doing to use Export-Csv? How can I "stage" the 10 lines which need to be converted into a single .csv row?