Monday, August 29, 2022

[FIXED] How to add quotes and commas in PowerShell?

Issue

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"


Solution

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.



Answered By - mklement0
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.