powershell core 7.1.2 或 7.2 中带重音的法语字符不起作用

gee*_*972 4 powershell

在 powershell 核心(7.1.2)或 7.2 上,我没有带重音的法语字符“\xc3\xa9”或“\xc3\xa8”或“\xc3\xa0”,我有这个:

\n

\xc3\x83\xc2\xa0 日\xc3\x83\xc2\xa9j\xc3\x83\xc2\xa0 安装\xc3\x83\xc2\xa9es 和 derni\xc3\x83\xc2\xa8 的使用列表\xc3\x83\xc2\xa0 日

\n

它适用于 powershell windows 5.1。文字是这样的:

\n

列出 \xc3\xa0 日内\xc3\xa9j\xc3\xa0 install\xc3\xa9es 和 derni\xc3\xa8re mise \xc3\xa0 日的情况列表

\n

我在这两种情况下使用 IDE Visual Studio 代码。

\n

请问解决方案是什么?\n我已经尝试更改编码:utf8 或 utf 16,例如使用法语语言包

\n

例如,我尝试了这段代码,但它不起作用

\n
#affiche la tentative de mise \xc3\xa0 jour"\nfunction affichetentative {\n \n    #nom du serveur\n    $b=HOSTNAME.EXE\n    #chemin  o\xc3\xb9  est lecalis\xc3\xa9 le fichier de log du serveur\n    $path="C:\\LOGS\\log_$b.txt"\n    #affichage du texte ci-dessous dans un fichier de log\n    $c=Get-Date\n    $a="Liste des mises \xc3\xa0 jours d\xc3\xa9j\xc3\xa0 install\xc3\xa9es dans la derni\xc3\xa8re mise \xc3\xa0 jour le {0} " -f  $c\n    ADD-content -path $path -Encoding utf8BOM -value  $a  \n        \n    }\n affichetentative \n
Run Code Online (Sandbox Code Playgroud)\n

我的文件中有这样的输出:

\n

\xc3\x83\xc2\xa0 日\xc3\x83\xc2\xa9j\xc3\x83\xc2\xa0 安装\xc3\x83\xc2\xa9es 和 derni\xc3\x83\xc2\xa8 的使用列表\xc3\x83\xc2\xa0 今天 16/02/2021 22:13:41

\n

即使我在 Visual Studio 代码上配置 utf8BOM 或 UTF-16LE,它也不起作用

\n

mkl*_*nt0 6

这意味着您的文件是 UTF8 编码的,但没有 BOM

\n
    \n
  • 警告:如果您使用Add-Content追加现有文件(非空),PowerShell会匹配(可能推断出的)现有编码忽略-Encoding参数
  • \n
\n

虽然 PowerShell (Core) 7+ 可以正确读取此类文件,但Windows PowerShell却不能,因为它在没有 BOM 的情况下假定采用ANSI编码;这适用于显式读取的文件和隐式读取的Get-Content代码文件。

\n

默认情况下,您希望两个PowerShell 版本都能正确解释的任何文件都应该是带有 BOM的 UTF8 编码(或 UTF16-LE 编码,PowerShell 称之为Unicode,它始终具有 BOM)。

\n

陷阱是现代编辑器(例如 Visual Studio Code)默认创建无 BOM文件,因为 UTF8 被假定为当今的默认编码,并且因为某些实用程序(尤其是具有 Unix 传统的实用程序)不期望BOM,甚至可能误解为数据

\n
    \n
  • 但是,正如filimonic指出的那样,您可以将Visual Studio Code配置为默认使用BOM创建 UTF8 文件(也可以仅针对 PowerShell 源代码文件) - 请参阅文档
  • \n
\n
\n

Windows PowerShell来看,问题可以演示如下:

\n
# Use a .NET API directly to create a test file.\n# .NET APIs create BOM-*less* UTF-8 files by default.\n[IO.File]::WriteAllText(\n  "$PWD/test.txt",\n  \'Liste des mises \xc3\xa0 jours d\xc3\xa9j\xc3\xa0 install\xc3\xa9es dans la derni\xc3\xa8re mise \xc3\xa0 jour\'\n)\n\n# Now read it with Get-Content on Windows PowerShell, which\n# results in MISINTERPRETATION.\n# Note: In PowerShell (Core) 7+, this works correctly.\nGet-Content test.txt\n
Run Code Online (Sandbox Code Playgroud)\n

你会得到:

\n
Liste des mises \xc3\x83\xc2\xa0 jours d\xc3\x83\xc2\xa9j\xc3\x83\xc2\xa0 install\xc3\x83\xc2\xa9es dans la derni\xc3\x83\xc2\xa8re mise \xc3\x83\xc2\xa0 jour\n
Run Code Online (Sandbox Code Playgroud)\n

因为 UTF8 编码被误解为活动 ANSI 代码页的编码。

\n

通过传递-Encoding utf8Get-Content,您可以避免该问题。

\n