简体   繁体   English

从字符串解析Powershell中的CSV?

[英]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. 我正在读取具有Get-Content的文件,对其进行一些修改,然后我有了CSV的结构,可以做进一步的工作。 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. 如果我这样做,可以先进行Out-File,然后进行Import-CSV,则可以正常工作,但是我想摆脱这种开销,并从我编辑的字符串中将其解析为CSV。 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. 我面临的问题是,我的CSV字段由逗号分隔,并用引号引起来,但CSV中的某些列包含多行字符串,其中包含逗号,但这些逗号不是分隔符。 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. 但是由于“不是delim逗号”,CSV的结构被错误地解析。

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是适当的对象,则字段内的逗号(用引号引起来)应该不会有问题。

$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 结果是一样的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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