这是我用来将"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:appsMVPSIJAMSAgentTempJAMSTemp13142.ps1:17 char:51
Error: + $content = '"segment99" ' + [io.file]::ReadAllText <<<< ($_.FullName)
Error: + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
Error: + FullyQualifiedErrorId : DotNetMethodException
Error:
我在一个有20个文件的文件夹上运行这段代码,每个文件超过2gb。
我该如何解决这个问题?
将头文件+大文件复制到新文件将不太容易出现内存不足异常(对于相同大小的文件):
$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"
}
这不是最优的代码,但它解决了任务而不读取所有文本到内存:它将标题添加到第一行,然后输出其他行。另外,请注意,如果输入文件为空,它什么也不做。
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')
}