将文件转换为 UTF-8:Get-Content:抛出“System.OutOfMemoryException”类型的异常

Mar*_*Ann 4 powershell encoding utf-8

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

$files = Get-ChildItem 'E:\datamig_bkp_SCMDB\data\bigfiles' -Recurse |
         ? {Test-Path $_.FullName -PathType Leaf}
foreach ($file in $files) {
    $content = Get-Content $file.FullName
    $content | Out-File $file.FullName -Encoding UTF8
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Get-Content:抛出“System.OutOfMemoryException”类型的异常。
行:3 字符:16
+ $content = 获取内容$file.FullName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : InvalidOperation: (:) [获取内容],OutOfMemoryException
    + FullQualifiedErrorId : ProviderContentReadError,Microsoft.PowerShell.Commands.GetContentCommand

Ans*_*ers 5

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

$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
}
Run Code Online (Sandbox Code Playgroud)

正如 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
}
Run Code Online (Sandbox Code Playgroud)