Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change encoding of Powershell created file to UTF8 instead of UCS-2 LE

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.

like image 691
null Avatar asked Mar 12 '23 03:03

null


1 Answers

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
like image 119
Andrey Marchuk Avatar answered Apr 06 '23 04:04

Andrey Marchuk