【问题标题】:how to split a csv file into small chunks with headers using powershell如何使用 powershell 将 csv 文件拆分为带有标题的小块
【发布时间】:2023-02-02 18:41:40
【问题描述】:

我正在使用以下代码将大型 csv 文件拆分为块。但是标头没有附加输出文件。

这是 powershell 脚本:

$InputFilename = Get-Content 'C:\Users\Sridhar\Downloads\Leads.csv'
$destinationPath = 'C:\Users\Sridhar\Downloads\'
$OutputfilenamePattern = 'leads_'
$LineLimit = 500
$line = 0 
$i = 0
$file = 0
$start = 0
$header = $InputFilename[0]
while ($line -le $InputFilename.Length){
 if($i -eq $LineLimit -Or $line -eq $Inputfilename.Length){
    $file++
    $Filename = "$destinationPath$OutputfilenamePattern$file.csv"   
    $InputFilename[$start..($line-1)] | Out-file $Filename -Force -Encoding utf8
    $start =$line;
    $i = 0
    Write-Host "$Filename"
}
$i++
$line++
}

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    有关完整的解释,请参阅:Mastering the (steppable) pipeline

    $BatchSize = 500
    Import-Csv .Leads.csv |
        ForEach-Object -Begin {
            $Index = 0
        } -Process {
            if ($Index % $BatchSize -eq 0) {
                $BatchNr = [math]::Floor($Index++/$BatchSize)
                $Pipeline = { Export-Csv -notype -Path .leads_$BatchNr.csv }.GetSteppablePipeline()
                $Pipeline.Begin($True)
            }
            $Pipeline.Process($_)
            if ($Index++ % $BatchSize -eq 0) { $Pipeline.End() }
        } -End {
            $Pipeline.End()
        }
    

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多