1

I have a Powershell script that is failing due to unicode characters in it:

MyScript.ps1:

Write-Host "Installing 無書籤..."

When I run this script from Powershell command line, I get the following error:

enter image description here

I gather the issue is Powershell is running in ASCII or some other non-unicode mode. I tried changing it like this:

$OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8

But the error still persists. How do I get Powershell to run my script?

Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212

2 Answers2

1

The screen shot implies that you're using Windows PowerShell, which interprets BOM-less *.ps1 files as ANSI-encoded (using the usually single-byte ANSI code page determined by the legacy system locale); by contrast, PowerShell [Core] v6+ now assumes UTF-8.

Therefore, for Windows PowerShell to correctly interpret CJK characters you must save your *.ps1 file using a Unicode encoding with BOM; given that PowerShell source code itself uses ASCII-range characters (resulting in a mix of Latin and CJK characters), the best choice is UTF-8 with BOM.


As for what you tried:

$OutputEncoding = [Console]::OutputEncoding = [Text.UTF8Encoding]::UTF8

These settings only apply when PowerShell communicates with external programs - see this answer.

mklement0
  • 382,024
  • 64
  • 607
  • 775
1

First, write and save your script, which contains Unicode characters, in the Windows PowerShell ISE program Then you can edit it with any program like visual code or ... This method should be useful.

Nima
  • 11
  • 1