由于 unicode 字符,Powershell 脚本无法 运行

Powershell script fails to run due to unicode character

我有一个 Powershell 脚本由于其中包含 unicode 字符而失败:

MyScript.ps1:

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

当我从 Powershell 命令行 运行 此脚本时,出现以下错误:

我收集到的问题是 Powershell 运行正在使用 ASCII 或其他一些非 unicode 模式。我试过这样改变它:

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

但错误仍然存​​在。如何让 Powershell 进入 运行 我的脚本?

屏幕截图表明您正在使用 Windows PowerShell,它解释 BOM-less *.ps1 文件作为 ANSI 编码(通常使用由遗留系统区域设置确定的单字节 ANSI 代码页);相比之下,PowerShell [Core] v6+ 现在采用 UTF-8。

因此,要使 Windows PowerShell 正确解释 CJK 字符 ,您必须使用 Unicode编码with BOM;鉴于 PowerShell 源代码本身使用 ASCII 范围的字符(导致混合了拉丁字符和 CJK 字符),最佳选择是 UTF-8 with BOM.


至于你试过的

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

这些设置仅在 PowerShell 与外部程序通信时适用 - 参见

首先,在 Windows PowerShell ISE 程序中编写并保存包含 Unicode 字符的脚本 然后你可以用任何程序编辑它,比如可视化代码或...... 这个方法应该有用。