【问题标题】:Memory optimized powershell Out-File -Encoding utf8 without BOM for large files内存优化的powershell Out-File - 为大文件编码没有BOM的utf8
【发布时间】:2014-04-04 12:28:46
【问题描述】:

所以我在 powershell 中运行一个外部命令,将 mysqldump.exe 输出通过管道传输到一个 .sql 文件中。

& "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe" @arguments | Out-File -Encoding utf8 $backupFilePath\$database.sql

首先,文件以 UCS2 编码输出。我设法弄清楚您可以将 Out-File 命令上的编码设置为 -Encoding utf8。但它带有字节顺序标记。有什么方法可以明确指定您不想要字节顺序标记?

我尝试使用 WriteAllLines 转换文件,但是这个数据库 .sql 文件输出的大小为 3GB,它会破坏内存。

有什么想法吗?

【问题讨论】:

  • 我相信这里已经回答了。 stackoverflow.com/questions/5596982/…
  • 您是否有超出 ascii 范围的字符?如果没有,请使用-enc ascii
  • @SunnyChakraborty 正如 OP 指出的那样,使用 WriteAllLines 并不是输出这么大(~3GB)的好选择。
  • 是的,我确实有 ASCII 范围之外的字符。我最终做的是从我的 Powershell 脚本中调用一个批处理脚本。不是一个很好的解决方案,但至少它有效。如果有人对此有解决方案,我非常想听听!
  • 对于那些不知道的人; BOM = 字节顺序标记。三个字符放置在文件开头(0xEF、0xBB、0xBF),看起来像“”

标签: mysql powershell encoding utf-8


【解决方案1】:
Function Out-FileUtf8NoBom {

  [CmdletBinding()]
  param(
    [Parameter(Mandatory, Position=0)] [string] $LiteralPath,
    [switch] $Append,
    [switch] $NoClobber,
    [AllowNull()] [int] $Width,
    [Parameter(ValueFromPipeline)] $InputObject
  )

  [Environment]::CurrentDirectory = $PWD
  $LiteralPath = [IO.Path]::GetFullPath($LiteralPath)

  if ($NoClobber -and (Test-Path $LiteralPath)) { 
    Throw [IO.IOException] "The file '$LiteralPath' already exists."
  }

  $sw = New-Object IO.StreamWriter $LiteralPath, $Append

  $htOutStringArgs = @{}
  if ($Width) {
    $htOutStringArgs += @{ Width = $Width }
  }

  try {
    $Input | Out-String -Stream @htOutStringArgs | % { $sw.WriteLine($_) }
  } finally {
    $sw.Dispose()
  }

}


Function FixEncoding([string] $path)
{
    [IO.SearchOption] $option = [IO.SearchOption]::AllDirectories;
    [String[]] $files = [IO.Directory]::GetFiles((Get-Item $path).FullName, '*.*', $option);
    foreach($file in $files)
    {
        "Converting $file...";
        Get-Content $file | Out-FileUtf8NoBom $file
    }
}

您可以将其用作FixEncoding("C:\path\to\files\")

【讨论】:

    猜你喜欢
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2020-09-01
    • 2020-12-08
    • 1970-01-01
    • 2015-12-12
    • 2011-06-16
    相关资源
    最近更新 更多