Powershell 将双引号添加到所有以逗号分隔的列,但不包括已用双引号括起来的逗号

Powershell 将双引号添加到所有以逗号分隔的列,但不包括已用双引号括起来的逗号,powershell,csv,Powershell,Csv,我试过的是 (导入csv C:\file.csv)|导出csv C:\file.csv-NoTypeInformation-编码UTF8 上述代码可以正常工作,但即使对于文件大小也会花费一些时间执行您可以通过使用导入csv而不是使用import csvcmdlet来加快该过程 如果这确实更快,请尝试: Add-Type -AssemblyName 'Microsoft.VisualBasic' # you'll need to use the full absolute path to the

我试过的是

(导入csv C:\file.csv)|导出csv C:\file.csv-NoTypeInformation-编码UTF8


上述代码可以正常工作,但即使对于文件大小也会花费一些时间执行您可以通过使用导入csv而不是使用
import csv
cmdlet来加快该过程

如果这确实更快,请尝试:

Add-Type -AssemblyName 'Microsoft.VisualBasic'

# you'll need to use the full absolute path to the file
$file   = "C:\file.csv"

# older PowerShell versions use:
# $parser = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser $file
$parser = [Microsoft.VisualBasic.FileIO.TextFieldParser]::new($file)
$parser.SetDelimiters(',')
$header = $parser.ReadFields()

$csv = while (!$parser.EndOfData) {
    $i = 0
    $row = [ordered]@{}
    foreach ($field in $parser.ReadFields()) {
        $row[$header[$i++]] = $field
    }
    [PSCustomObject]$row
}
# clean up
$parser.Dispose()

# export the csv in UTF8
$csv | Export-Csv -Path $file -NoTypeInformation -Encoding UTF8

由于逗号从一开始就不包含在双引号中(这是一个文件必须是真正的CSV文件的要求),我认为解决这个问题是不可能的。没有办法知道逗号是分隔符还是文本的一部分,除非它在双引号内,或者你从一开始就使用了另一个分隔符。你的问题是什么?你的代码不起作用(对我来说是这样)还是需要很多时间?@DanielBjörk..第二个字段中的逗号被引用了,所以是的,这是有效的Csv。啊,现在我明白了。但是我看不出你想要实现什么,因为你只是说这是可行的,但需要花费一些时间。@T-Me代码正在运行,但我想知道是否有其他方法可以更快地处理。
row 1 - "textOne","text with a,comma","","sample"

row 2 - "textTwo","demo text","","stack"
Add-Type -AssemblyName 'Microsoft.VisualBasic'

# you'll need to use the full absolute path to the file
$file   = "C:\file.csv"

# older PowerShell versions use:
# $parser = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser $file
$parser = [Microsoft.VisualBasic.FileIO.TextFieldParser]::new($file)
$parser.SetDelimiters(',')
$header = $parser.ReadFields()

$csv = while (!$parser.EndOfData) {
    $i = 0
    $row = [ordered]@{}
    foreach ($field in $parser.ReadFields()) {
        $row[$header[$i++]] = $field
    }
    [PSCustomObject]$row
}
# clean up
$parser.Dispose()

# export the csv in UTF8
$csv | Export-Csv -Path $file -NoTypeInformation -Encoding UTF8