将Powershell创建的文件的编码更改为UTF8而不是UCS-2 LE [英] Change encoding of Powershell created file to UTF8 instead of UCS-2 LE
问题描述
我正在使用Powershell创建文件,我需要将此文件进行UTF8编码,到目前为止,我尝试过的所有尝试均以失败告终.
I'm using powershell to create a file, I need this file to be UTF8 Encoded, thus far all of the attempts I've tried have failed.
在Notepad ++中检查文件会显示UCS-2 LE BOM作为编码. powershell是否可以改用UTF8?
Inspecting the file in Notepad++ shows UCS-2 LE BOM as the encoding. Is it possible for powershell to use UTF8 instead?
到目前为止,我已经尝试对utf8进行编码,目前正在使用[IO.File]::WriteAllLines($filename, $text)
So far I've tried -encoding utf8 and currently I'm using [IO.File]::WriteAllLines($filename, $text)
当我在控制台中收到此错误,但是正在创建文件时,可能存在一个潜在的问题(请原谅,这是Powershell的一个非常新的问题),导致该问题.
There may be an underlying issue (forgive me, very new to Powershell) that is causing the problem as I receive this error in the console however the file is being created:
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
在给出答案后进行编辑以提供更多信息.
Edited after answer given to provide more info.
文件中的详细信息:
write-host "Creating Application.conf in UTF-8"
$filename = "c:\application.conf"
[IO.File]::WriteAllLines($filename, $text, [System.Text.Encoding]::UTF8)
根据上述,控制台中的输出仍然错误.
the output in the console is still erroring as per the above.
推荐答案
您需要使用WriteAllLines
的不同重载:
File.WriteAllLines方法(String,String [],Encoding),请参见此处: https://msdn.microsoft.com/zh-CN/library/3det53xh(v = vs.110).aspx
You need to use different overload of WriteAllLines
:
File.WriteAllLines Method (String, String[], Encoding), see here: https://msdn.microsoft.com/en-us/library/3det53xh(v=vs.110).aspx
它将是:
[IO.File]::WriteAllLines($filename, $text, [System.Text.Encoding]::UTF8)
当然可以使用PS方式:
And of course you can use PS way:
$text | Out-File $filename -encoding Utf8
这篇关于将Powershell创建的文件的编码更改为UTF8而不是UCS-2 LE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!