从powershell调用时,Iconv正在转换为UTF-16而不是UTF-8

fde*_*ego 4 powershell encoding utf iconv

尝试使用powershell脚本中的iconv将某些文件的编码从ISO-8859-1批量转换为UTF-8时出现问题.

我有这个bat文件,工作正常:

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 
)
Run Code Online (Sandbox Code Playgroud)

我需要转换目录结构上的所有文件,所以我编写了这个其他脚本,这次使用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
  }
Run Code Online (Sandbox Code Playgroud)

使用此结果是将文件转换为UTF-16.我不知道我做错了什么.

任何人都可以帮我这个吗?对于PowerShell本身的编码可能是某种问题吗?

我正在使用W7和WXP以及LibIconv 1.9.2

Kei*_*ill 5

>本质上是使用Out-File cmdlet,其默认编码是Unicode.尝试:

iconv.exe ... | Out-File -Encoding Utf8
Run Code Online (Sandbox Code Playgroud)

或者使用params:

& "C:\Program Files\GnuWin32\bin\iconv.exe" -f iso-8859-1 -t utf-8 $inFileName |
   Out-File -Encoding Utf8 $outFileName 
Run Code Online (Sandbox Code Playgroud)

并且由于iconv.exe以UTF8输出,您必须告诉.NET控制台子系统如何像这样对stdin流进行intreprest(在iconv.exe之前执行此操作):

[Console]::OutputEncoding = [Text.Encoding]::UTF8 
Run Code Online (Sandbox Code Playgroud)