将Powershell创建的文件的编码更改为UTF8而不是UCS-2 LE

时间:2016-05-31 11:47:07

标签: powershell encoding utf-8

我使用PowerShell创建文件,我需要这个文件是UTF8编码的,到目前为止我尝试过的所有尝试都失败了。

在Notepad ++中检查文件显示UCS-2 LE BOM作为编码。 PowerShell是否可以使用UTF8?

到目前为止,我已尝试过-encoding utf8,目前我正在使用[IO.File]::WriteAllLines($filename, $text)

可能存在一个潜在的问题(原谅我,对Powershell来说很新)导致问题,因为我在控制台中收到此错误但是正在创建文件:

    Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
    + CategoryInfo          : InvalidArgument: (:) [Out-File], PSArgumentNullException
    + FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.OutFileCommand
    + PSComputerName        : 50.19.209.240

ChangeFileModeByMask error (3): The system cannot find the path specified.
    + CategoryInfo          : NotSpecified: (ChangeFileModeB...path specified.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : 50.19.209.240

编辑:

在给出答案后编辑以提供更多信息。

文件详情:

write-host "Creating Application.conf in UTF-8"
$filename = "c:\application.conf"
[IO.File]::WriteAllLines($filename, $text, [System.Text.Encoding]::UTF8) 

控制台中的输出仍然是错误的,如上所述。

2 个答案:

答案 0 :(得分:2)

您需要使用WriteAllLines的不同重载: File.WriteAllLines方法(String,String [],编码),见这里:https://msdn.microsoft.com/en-us/library/3det53xh(v=vs.110).aspx

它将是:

[IO.File]::WriteAllLines($filename, $text, [System.Text.Encoding]::UTF8)

当然你可以使用PS方式:

$text | Out-File $filename -encoding Utf8

答案 1 :(得分:1)

任何特殊原因,为什么你使用.net类? 您还可以使用set-content cmdlet。

"text" | Set-Content -Encoding UTF8 -Path "c:\path\file.txt"