PowerShellscript,错误的文件编码对话

Gus*_*der 4 powershell character-encoding iconv

我有一个用于文件字符编码对话的PowerShell脚本.

Get-ChildItem -Path D:/test/data -Recurse -Include *.txt |
ForEach-Object {
  $inFileName = $_.DirectoryName + '\' + $_.name
  $outFileName = $inFileName + "_utf_8.txt"
  Write-Host "windows-1251 to utf-8: " $inFileName -> $outFileName  
  E:\bin\iconv\iconv.exe -f cp1251 -t utf-8 $inFileName > $outFileName
}
Run Code Online (Sandbox Code Playgroud)

但它不是utf-8,而是将文件字符编码转换为utf-16.当我从命令行调用iconv实用程序时,它工作正常.

我错了什么?

ajk*_*ajk 5

将输出重定向到文件时,Powershell使用Unicode作为默认编码.您可以Out-File使用-Encoding UTF8交换机来管道,而不是使用重定向运算符.

E:\bin\iconv\iconv.exe -f cp1251 -t utf-8 $inFileName | Out-File -FilePath $outFileName -Encoding UTF8
Run Code Online (Sandbox Code Playgroud)

以下TechNet文章提供了更多信息(相当于Get-Help Out-File -fullPowershell v2).

如果它对您的场景有帮助,值得注意的是您也可以使用Powershell进行编码转换.

Get-Content $inFileName -Encoding ASCII |
Out-File -FilePath $outFileName -Encoding UTF8
Run Code Online (Sandbox Code Playgroud)

  • @ Gustav.Calder有,但它没有出现在'Get-Content`的帮助中,因为它是FileSystem提供者提供的动态参数.您可以在`Get-Help FileSystem`中找到更多信息. (2认同)