内存优化的PowerShell Out-File -Encoding utf8,无需大型文件的BOM

时间:2014-03-03 12:40:32

标签: mysql powershell encoding utf-8

所以我在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,它会破坏内存。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

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\")