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

I use powershell to create a file, I need this file to encode UTF8, until all the attempts that I tried failed.

File validation in Notepad ++ shows the UCS-2 LE BOM as an encoding. Is it possible to use PowerShell instead of UTF8?

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

A major problem may arise (forgive me, very new to Powershell), which causes the problem, as I get this error in the console, but the file is 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 the response to provide additional information.

Details from file:

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

console output is still an error as described above.

0
source share
2 answers

You need another WriteAllLines overload: File.WriteAllLines (String, String [], Encoding) method, 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 the PS method:

 $text | Out-File $filename -encoding Utf8 
+1
source

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

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

All Articles