1

I have a CSV file where I only need 1 Column Called "SerialNumber" I need to combine the text lines, remove any blank space, add each line in quotes and separate by comma.

So far I have multiple miles of code that work, but it adds quotes at the end and doesn't add quotes in the beginning.

$SerialList = import-csv .\log.csv | select -ExpandProperty Serialnumber | Out-File -FilePath .\Process.txt
(gc process.txt) | ? {$_.trim() -ne "" } | set-content process.txt
gc .\process.txt | %{$_ -replace '$','","'} | out-file process1.csv
Get-Content .\process1.csv| foreach {
$out = $out + $_
}
$out| Out-File .\file2.txt

Output:

SerialNumber

1234

1234

4567

4567

Expected Output:

"1234","1234","4567","4567"

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Razo559
  • 23
  • 3

1 Answers1

2

Try the following (PSv3+):

(Import-Csv .\log.csv).SerialNumber -replace '^.*$', '"$&"' -join "," > .\file2.txt
  • (Import-Csv .\log.csv).SerialNumber imports the CSV file and .SerialNumber uses member-access enumeration to extract the SerialNumber column values as an array.

  • -replace '^.*$', '"$&"' encloses each array element in "...".

    • Regex ^.*$ matches each array element in full.
    • Replacement expression "$&" replaces the element with what was matched ($&) enclosed in " chars. - for background, see this answer
  • -join "," joins the resulting array elements with , as the separator.

mklement0
  • 382,024
  • 64
  • 607
  • 775