简体   繁体   中英

Parsing CSV in Powershell from a string?

I'm reading a file with Get-Content, do some modifications to it, and I have a structure of a CSV after that, which do further stuff with. If I do and Out-File, and then Import-CSV it, works fine, but I want to get rid of this overhead, and parse it to CSV from my edited string. The problem I'm facing is, that my CSV fields are delimited by commas, and are enclosed in quotation marks, BUT, some of the columns in my CSV contain multiline strings, with commas in them, but those commas are not delimiters. I was trying to do

$mycsvcontent | ConvertFrom-CSV

and

$mycsvcontent | ConvertFrom-CSV -Header "Column1","Column2","etc..."

But because of the "not delim commas", the structure of the CSV is parsed incorrectly.

How can I achieve this?

Commas within fields (enclosed in quotation marks) should not be a problem, if your $mycsvcontent is an appropriate object.

$mycsvcontent = {"a,a","b","c,c"}
$mycsvcontent | ConvertFrom-CSV -Header "Column1","Column2","etc..."

returns

Column1 Column2 etc... 
------- ------- ------  
a,a     b       c,c

If it is just an array, try the following:

$mycsvcontent = @("a,a","b","c,c")
$f = '"' + $($mycsvcontent -join '","') + '"'
$f | ConvertFrom-CSV -Header "Column1","Column2","etc..."

The result is the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM