问题描述
在powershell脚本中尝试使用iconv将某些文件的编码从ISO-8859-1批量转换为UTF-8时遇到问题。
I have a problem while trying to batch convert the encoding of some files from ISO-8859-1 to UTF-8 using iconv in a powershell script.
I有这个蝙蝠文件,就可以了:
I have this bat file, that works ok:
for %%f in (*.txt) do (
echo %%f
C:\"Program Files"\GnuWin32\bin\iconv.exe -f iso-8859-1 -t utf-8 %%f > %%f.UTF_8_MSDOS
)
我需要转换目录结构上的所有文件,所以我编写了另一个脚本,这次使用powershell:
I need to convert all files on the directories structure, so I programmed this other script, this time using powershell:
Get-ChildItem -Recurse -Include *.java |
ForEach-Object {
$inFileName = $_.DirectoryName + '\' + $_.name
$outFileName = $inFileName + "_UTF_8"
Write-Host Convirtiendo $inFileName -> $outFileName
C:\"Program Files"\GnuWin32\bin\iconv.exe -f iso-8859-1 -t utf-8 $inFileName > $outFileName
}
使用此结果是将文件转换为UTF-16 。我不知道我在做什么错。
And using this the result is the files be converted to UTF-16. I have no clue about what I am doing wrong.
有人可以帮我这个忙吗? powershell本身的编码是否会出现某种问题?
Could anyone help me with this? Could be it some kind of problem with the encoding of powershell itself?
我正在使用W7,WXP和LibIconv 1.9.2
I am using W7 and WXP and LibIconv 1.9.2
推荐答案
>
本质上使用的是Out-File cmdlet,其默认编码为Unicode。尝试:
>
essentially is using the Out-File cmdlet who's default encoding is Unicode. Try:
iconv.exe ... | Out-File -Encoding Utf8
或带有参数:
& "C:\Program Files\GnuWin32\bin\iconv.exe" -f iso-8859-1 -t utf-8 $inFileName |
Out-File -Encoding Utf8 $outFileName
由于iconv.exe在UTF8中输出,您必须告诉.NET控制台子系统如何像这样解释stdin流(在iconv.exe之前执行此操作):
And since iconv.exe is outputting in UTF8, you have to tell the .NET console subsystem how to intrepret the stdin stream like so (execute this before iconv.exe):
[Console]::OutputEncoding = [Text.Encoding]::UTF8
这篇关于从Powershell调用Iconv时,它将转换为UTF-16而不是UTF-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!