使用PowerShell移除CSV行内非法CRLF实现SQL Server历史数据导入
PowerShell CSV异常换行修复方案
核心逻辑
利用「正确行必须包含121个逗号」的明确规则,对读取的内容做逗号计数,未达到计数要求就将下一段内容拼接至当前行,自动过滤非行尾的CRLF换行。
可直接运行的脚本
# 配置参数 $sourceDir = "C:\你的原始CSV文件目录" $outputDir = "C:\处理后的CSV输出目录" $logPath = "C:\异常行日志.txt" $requiredCommas = 121 # 122列对应121个逗号 # 初始化目录和日志 if (-not (Test-Path $outputDir)) { New-Item -ItemType Directory -Path $outputDir | Out-Null } "处理开始时间: $(Get-Date)" | Out-File $logPath -Append # 批量处理所有CSV文件 Get-ChildItem -Path $sourceDir -Filter *.csv | ForEach-Object { $sourceFile = $_.FullName $outputFile = Join-Path $outputDir $_.Name $currentLine = "" $lineCount = 0 $reader = New-Object System.IO.StreamReader($sourceFile) $writer = New-Object System.IO.StreamWriter($outputFile) while (($line = $reader.ReadLine()) -ne $null) { $currentLine += $line $commaCount = ($currentLine.ToCharArray() | Where-Object { $_ -eq ',' }).Count if ($commaCount -eq $requiredCommas) { # 符合要求,写入输出文件 $writer.WriteLine($currentLine) $currentLine = "" $lineCount++ } elseif ($commaCount -gt $requiredCommas) { # 异常行,写入日志 "文件:$($_.Name) 异常行序号:$lineCount 逗号数:$commaCount 内容:$currentLine" | Out-File $logPath -Append $currentLine = "" } } # 处理剩余未输出的内容 if ($currentLine -ne "") { "文件:$($_.Name) 末尾未完成行 内容:$currentLine" | Out-File $logPath -Append } $reader.Close() $writer.Close() Write-Host "已处理文件: $($_.Name) 有效行数: $lineCount" } "处理结束时间: $(Get-Date)" | Out-File $logPath -Append
注意事项
- 运行前请先备份所有原始CSV文件,脚本不会修改原文件,所有处理结果输出到指定的
$outputDir目录 - 针对单文件3.5万行的场景,单文件处理耗时小于1秒,365个文件可在1分钟内完成全部处理
- 所有不符合列数要求的异常行会单独记录到日志文件,可后续人工核对
- 处理后的文件结构与你预设的SSIS连接配置完全兼容,可直接导入SQL Server
内容的提问来源于stack exchange,提问作者mf.cummings
相关产品推荐
相关产品推荐

