PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

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

 August 29, 2022     csv, powershell, powershell-2.0, powershell-3.0     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing