PowerShellscript,错误的文件编码对话

PowerShellscript,错误的文件编码对话,powershell,character-encoding,iconv,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 -&

我有一个用于文件字符编码对话的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
}
但它将文件字符编码转换为utf-16而不是utf-8。当我从命令行调用iconv实用程序时,它工作正常


有什么不对吗?

将输出重定向到文件时,Powershell使用Unicode作为默认编码。您可以使用
-Encoding UTF8
开关通过管道连接到
输出文件,而不是使用重定向操作符

E:\bin\iconv\iconv.exe -f cp1251 -t utf-8 $inFileName | Out-File -FilePath $outFileName -Encoding UTF8
以下TechNet文章提供了更多信息(相当于Powershell v2中的
获取帮助文件-full

如果这对您的场景有帮助,那么值得注意的是,您还可以使用Powershell进行编码转换

Get-Content $inFileName -Encoding ASCII |
Out-File -FilePath $outFileName -Encoding UTF8

您确定Get-Content cmdlet有这样一个参数作为-Encoding吗?@Gustav.Calder-是的is@Gustav.Calder有,但它没有出现在
Get Content
的帮助中,因为它是由文件系统提供程序提供的动态参数。您可以在
获取帮助文件系统
中找到更多信息。