2014-03-03 32 views
3

所以我在PowerShell中運行一個外部命令來將mysqldump.exe輸出管道輸出到一個.sql文件中。內存優化的powershell Out-File -Encoding utf8沒有BOM的大文件

& "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,並且它破壞了內存。

有什麼想法?

+4

我相信這是在這裏找到答案。 http://stackoverflow.com/questions/5596982/using-powershell-to-write-a-file-in-utf-8-without-the-bom –

+0

你有超過ascii範圍的字符?如果不是,請使用'-enc ascii'。 –

+1

@SunnyChakraborty正如OP指出的那樣,使用WriteAllLines並不是一個很好的選擇來輸出這個大的(〜3GB)。 –

回答

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