简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM