2011-11-15 34 views
3

を実行しているここで私は、フォルダ内のすべてのテキストファイル(1つずつ)の先頭に「segment99」を追加するために使用していますPowerShellスクリプトです:のOutOfMemoryException私の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ギガバイトを超えるごとに、このコードを実行しています。

私はこの問題を解決するにはどうすればよいですか?ヘッダファイルをコピーする+新しいファイルに大きなファイルは(そのサイズのファイルの場合)のOutOfMemory例外を起こしにくいだろう

答えて

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" 
} 
+0

これを試しましたか?何か必要なものはありません。 –

+1

@RomanKuzmin私は、out-fileコマンドレットでエンコーディングを忘れました。キャッチするためにありがとう。大きなファイル(> 2GB)でテストしてもうまく動作します(<1分) –

+2

ヘッダーファイルのエンコーディングは、test_export.txtファイルのエンコーディングと一致する必要があります。 –

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') 
} 
+1

これは私が提案することを考えていたものです。とにかく、 '。{process {' line? foreach-objectは私が思うように動作しますか? – manojlds

+1

はい、 'ForEach-Object'は(基本的に)'。{process {..}} 'と同じですが、ずっと遅いです。約2GBの場合は重要です。 –

+0

ああ。これは '' {'の表記ですか? – manojlds

関連する問題