运行PowerShell脚本时出现OutOfMemoryException

时间:2011-11-15 05:54:14

标签: powershell

这是我用来将“segment99”添加到文件夹中所有文本文件的开头(逐个)的PowerShell脚本:

Set Environmental Variables:

$PathData = '<<ESB_Data_Share_HSH>>\RwdPnP'

Go to each text file in the specified folder and add header to the file:

Get-ChildItem $PathData -filter 'test_export.txt'|%{

$content = '"segment99" ' + [io.file]::ReadAllText($_.FullName)
[io.file]::WriteAllText(($_.FullName -replace '\.txt$','_99.txt'),$content)

}

这给了我以下错误:

Error: Exception calling "ReadAllText" with "1" argument(s): "Exception of type 'Syste
Error: m.OutOfMemoryException' was thrown."
Error: At D:\apps\MVPSI\JAMS\Agent\Temp\JAMSTemp13142.ps1:17 char:51
Error: + $content = '"segment99" ' + [io.file]::ReadAllText <<<< ($_.FullName)
Error:     + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
Error:     + FullyQualifiedErrorId : DotNetMethodException
Error:

我在一个包含20个文件的文件夹上运行此代码,每个文件超过2 GB。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

将头文件+大文件复制到新文件将不太容易出现内存异常(对于那个大小的文件):

$header = '"segment99"'
$header | out-file header.txt -encoding ASCII
$pathdata = "."
Get-ChildItem $PathData -filter 'test_export.txt' | %{
  $newName = "{0}{1}{2}" -f $_.basename,"_99",$_.extension
  $newPath = join-path (split-path $_.fullname) $newname
  cmd /c copy /b "header.txt"+"$($_.fullname)" "$newpath"
}

答案 1 :(得分:2)

这不是最佳代码,但它解决了任务而无需将所有文本读取到内存:它将标题添加到第一行,然后输出其他行。另请注意,如果输入文件为空,则不执行任何操作。

Get-ChildItem $PathData -Filter 'test_export.txt' | %{
    $header = $true
    Get-Content $_.FullName | .{process{
        if ($header) {
            '"segment99" ' + $_
            $header = $false
        }
        else {
            $_
        }
    }} | Set-Content ($_.FullName -replace '\.txt$', '_99.txt')
}
相关问题