将文件转换为UTF-8:获取内容:引发了类型为'System.OutOfMemoryException'的异常

时间:2018-10-02 09:22:57

标签: powershell encoding utf-8

我正尝试将dat文件的大文件转换为UTF-8,以将其加载到数据库中(文件上带有日语字符)。最大文件为17 GB,整个目录为34 GB。下面是我的PowerShell脚本。

return x or y

我遇到以下错误:

Get-Content : Exception of type 'System.OutOfMemoryException' was thrown.
At line:3 char:16
+     $content = Get-Content $file.FullName
+                ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-Content], OutOfMemoryException
    + FullyQualifiedErrorId : ProviderContentReadError,Microsoft.PowerShell.Commands.GetContentCommand

1 个答案:

答案 0 :(得分:3)

不要将大文件读入内存。将输出写入新的(临时)文件,然后删除原始文件并将临时文件移到其位置。

$tmp = 'C:\path\to\temp.txt'
Get-ChildItem 'E:\datamig_bkp_SCMDB\data\bigfiles' -Recurse | Where-Object {
    -not $_.PSIsContainer
} | ForEach-Object {
    $file = $_.FullName
    Get-Content $file | Out-File $tmp -Encoding UTF8
    Remove-Item $file -Force
    Move-Item $tmp $file
}

正如TheIncorrigible1在注释中指出的那样,当您使用PowerShell v3或更高版本时,可以对代码进行一些简化:

$tmp = 'C:\path\to\temp.txt'
Get-ChildItem 'E:\datamig_bkp_SCMDB\data\bigfiles' -Recurse -File | ForEach-Object {
    $file = $_.FullName
    Get-Content $file | Out-File $tmp -Encoding UTF8
    Remove-Item $file -Force
    Move-Item $tmp $file
}