【问题标题】:Convert files to UTF-8 : Get-Content : Exception of type 'System.OutOfMemoryException' was thrown将文件转换为 UTF-8:Get-Content:抛出“System.OutOfMemoryException”类型的异常
【发布时间】:2018-10-02 09:22:57
【问题描述】:

我正在尝试将 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
}

我遇到以下错误:

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

【问题讨论】:

    标签: powershell encoding utf-8


    【解决方案1】:

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

    $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 在 cmets 中指出的那样,当您拥有 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
    }
    

    【讨论】:

    • 而不是Where-Object,使用-File 开关会更具可读性。您还可以将FileInfo 对象直接通过管道传递给Get-Content
    • @TheIncorrigible1 参数 -File 是在 PowerShell v3 中引入的。我更喜欢让我的答案向后兼容,所以我倾向于避免使用较新的功能,除非问题表明用户正在运行足够新的版本。至于管道文件对象到Get-Content:我看不到这里的优势,因为每个文件都应该单独处理,并且删除原始文件后移动临时文件需要完整路径。我不确定 FileInfo 对象中的信息是否在文件删除后仍然存在,所以我采取了安全的方法。
    • 它只是使使用管道而不是使用位置参数的代码更具可读性,imo。 FileInfo 对象在项目本身作为 FYI 被删除后被保留。 $_ | Get-Content | Out-File -FilePath $tmp -Encoding utf8等
    • 我不反对可读性方面。不过,我仍然强调兼容性,b/c 这样答案对更广泛的受众有用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2020-11-25
    相关资源
    最近更新 更多