Change encoding of Powershell created file to UTF8

2019-06-03 02:36发布

问题:

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.

Inspecting the file in Notepad++ shows UCS-2 LE BOM as the encoding. Is it possible for powershell to use UTF8 instead?

So far I've tried -encoding utf8 and currently I'm using [IO.File]::WriteAllLines($filename, $text)

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

Edit:

Edited after answer given to provide more info.

Details from the file:

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.

回答1:

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

It will be:

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

And of course you can use PS way:

$text | Out-File $filename -encoding Utf8


回答2:

Any special reason, why you use .net classes? You can also use set-content cmdlet.

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