MysqlDump from Powershell and Windows encoding

2020-06-12 04:42发布

问题:

I'm doing an export from command line on ms-dos with mysqldump:

& mysqldump -u root -p --default-character-set=utf8 -W -B dbname 
> C:\mysql_backup.sql

My database/tables are encoded with UTF-8 and I specify the same encoding when I did the dump. But when I open the file with Notepad++ or Scite I see an encoding of UTF-16 (UCS-2). If I don't convert the file with iconv to UTF-8 before running the import I got an error.

It seems that MS-DOS / CMD.exe is redirecting by default with UTF-16. Can I change this ?

A side note: I use Powershell to call mysqldump.

UPDATE: it seems that it occurs only when calling mysqldump from Powershell. I change the command line with the one I use in my PS script

回答1:

By default PowerShell represents text as Unicode and when you save it to a file it saves as Unicode by default. You can change the file save format by using the Out-File cmdlet instead of the > operator e.g.:

... | Out-File C:\mysql_backup.sql -Encoding UTF8

You may also need to give PowerShell a hint on how to interpret the UTF8 text coming from the dump utiltiy. This blog post shows how to handle this scenario in the event the utility isn't outputting a proper UTF8 BOM.