首页 > 解决方案 > 如何在 Powershell 中使用 Stream Writer 向文件中添加行

问题描述

我有 6GB 的插入语句 sql 文件,我想在每 150 行之后添加一个 GO 语句。该文件共有 9M 行。

我发现了一些使用 Powershell 脚本的代码,并且最推荐使用流或 .NET 命令来提高大文件的性能。

$reader = [System.IO.File]::OpenText("C:\src\customers1.sql")
$pathAndFilename = "c:\src\files\_customers_1.sql"
$streamout = new-object System.IO.StreamWriter $pathAndFilename
$batchSize = 150
$counter = 0
try {
    for ( $line = $reader.ReadLine(); $line -ne $null; $line = $reader.ReadLine() ) 
    { 
        $streamout.writeline($line)
        $counter +=1
        if ($counter -eq $batchsize)
        {   
            $counter =0
            $_ # send the current line to output
            if ($_ -match ", NULL, NULL") 
            {
                #Add Lines after the selected pattern 
                $line="GO"
                $streamout.writeline($line)
            }
        }
    }
}
finally {
    $reader.Close()
    $streamOut.close()
}

以上读取源文件并在 3 分钟内写入目标路径。但是,它不会在每 150 行代码之后编写 GO。似乎只是将文件复制过来。代码中有我遗漏的东西吗?

标签: powershellfilestream

解决方案


推荐阅读