Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OutOfMemoryException when running my PowerShell script

Tags:

powershell

Here's the PowerShell script I am using to add "segment99" to the beginning of all the text files (one by one) within a folder:

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)

}

This is giving me the following error:

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:

I am running this code on a folder that has 20 files, each over 2 GB.

How can I fix this?

like image 485
Nish87 Avatar asked Feb 05 '26 07:02

Nish87


1 Answers

Copying a header file + a large file to a new file will be less prone to outofmemory exceptions (for files of that size):

$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"
}
like image 78
jon Z Avatar answered Feb 09 '26 07:02

jon Z



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!