c-chavez
c-chavez

Reputation: 7496

Powershell logging from Invoke-Expression with encoding

I have an specific scenario where I have to log a batch file using Invoke-Expression in Powershell but my logs are being saved with "UCS-2 Little Endian" Encoding and I would like to save it with UTF-8 or any other encoding.

This is a simple example of what I'm trying to do:

batch file (test.bat):

echo Test

Powershell file (test.ps1):

Invoke-Expression "c:\test.bat > log.txt"

Is there a way I could change the encoding on log.txt?

Upvotes: 0

Views: 3084

Answers (1)

Paul
Paul

Reputation: 5861

You can try this:

C:\test.bat | Out-File C:\log.txt -Encoding UTF8

Or if for whatever reason you really have to use Invoke-Expression:

Invoke-Expression "C:\test.bat" | Out-File C:\log.txt -Encoding UTF8

Note that this will overwrite log.txt everytime. If you want to append to the file do this:

Invoke-Expression "C:\test.bat" | Out-File C:\log.txt -Encoding UTF8 -append

or

Invoke-Expression "C:\test.bat" | Add-Content C:\log.txt -Encoding UTF8

Upvotes: 1

Related Questions