2

I am making a simple PowerShell script to launch using the Task Scheduler. The script should create a file, launch a .exe-Program and redirect all the output to the newly created file.

This is what my script looks like now:

# script.ps1
$LogFile = "C:\a\very\long\path\to\logfile.log"
C:
cd 'C:\path\to\exe\directory\' > $LogFile
.\program.exe > $LogFile

The program outputs symbols of the German alphabet: Ää Öö Üü ß. When I launch the program without file writing, it output the symbol the way it should: ä, ü. However, when I redirect the output to the log file, ä turns into õ and ü turns into ³.

I tried appending chcp 65001 and $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }, but it didn't have any effect.

Funnily enough, this problem happens only in PowerShell. A similar script in Batch doesn't have this problem. Is there a way to fix it in PowerShell?

P. S. My PowerShell version is 5.1

2
  • Open your ps1 file using notepad++ and change the encoding type and save it... Should work.. Commented Jan 31, 2020 at 9:50
  • 2
    The cmdlet Out-File has a parameter -Encoding. Read the help to learn how to use it please. Commented Jan 31, 2020 at 9:51

1 Answer 1

2

From PowerShell, external program (.exe) output encoding is managed by [Console]::OutputEncoding. If you want UTF8, then that property needs to have a UTF8 encoding.

$BackupEncoding = [Console]::OutputEncoding
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
.\program.exe > $LogFile
[Console]::OutputEncoding = $BackupEncoding

Note: The above solution is UTF8 with BOM. In PowerShell Core 6.2+ and PowerShell 7, UTF8 with no BOM is the default encoding in these cases.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.