2014-02-18 28 views
1

我需要使用PowerShell文本,以CSV跨列拆分在PowerShell中

这是一个文本,向人们展示的重要性写下面的文字到CSV文件逗号和“Double 行情”。因此,这是非常重要的

我正在使用流编写器及其writeline()来实现上述。但是,在字符串“双引号”之后的第一个逗号之后的文本正在输出文件中的两个单元格之间分割。

我的输出是这样的:小区的

内容:这是一个文本,向人们展示 逗号和“双引号”的重要性。因此

小区2的内容:这是非常重要

我怎样才能显示在仅一个小区内的所有输入的文本?

这里是我的代码片断

$id = '12345' 
    $preamble = 'This is a text, to demonstrate the importance of comma and the "Double Quotes". Hence, it is very important' 
    $filename = "Comma.csv" 
    $currentDir = Get-Location 
    $outputcsv = Join-Path $currentDir $filename 
    $str = [System.IO.StreamWriter] $outputcsv 
    $newrow = "$id,`"$preamble`"" 
    $str.WriteLine($newrow) 
    $str.Close() 

回答

1

一般情况下,当你创建一个CSV文件与文本引号字符,您需要使用两个引号字符。因此字符串

This is a text, to demonstrate the importance of comma and the "Double Quotes". Hence, it is very important 

将进入CSV像下面

"This is a text, to demonstrate the importance of comma and the ""Double Quotes"". Hence, it is very important" 

在另一方面,由于您使用PowerShell中创建一个CSV文件,你或许应该使用的Export-CSV cmdlet的。

+0

谢谢robert.westerlund :)它的工作!由于我的程序中的输入文本正在从数据库中检索,我所要做的就是用双引号替换双引号。 – Syed1510

+0

您是否尝试过使用'Export-Csv'代替?我建议使用它而不是手动处理。它最终可能会为你节省很多麻烦。 –

+0

实际上,我的数据表中有一组需要写入csv文件的行。我可以直接使用MyDataTable | Export-Csv,但我必须为每行添加一些硬编码的列值。因此我觉得stream.writeline()是一个更好的选择。而且,Export-csv命令中的“-Append”开关导致了问题。 – Syed1510