PowerShell 5.1,使用 Out-File / Set-Content 和 utf8 输出到文本文件

问题描述 投票:0回答:1

我对如何在 PS 5.1 中解释这一点感到有点困惑: 首先,我尝试使用

Set-Content
Add-Content

创建一个文件
"# Script for running installers`n`n" | Out-File $InstallTools -Encoding utf8
"sleep 5" | Add-Content $InstallConsoleTools
"Start-Process -WindowStyle Hidden `"powershell.exe`" -ArgumentList `"-NoProfile -ExecutionPolicy Bypass -File `"`"$SetupScript`"`"`"" | Add-Content $InstallTools

输出一团糟:

# Script for running installers
sleep 5
S t a r t - P r o c e s s   - W i n d o w S t y l e   H i d d e n   " p o w e r s h e l l . e x e "   - A r g u m e n t L i s t   " - N o P r o f i l e   - E x e c u t i o n P o l i c y   B y p a s s   - F i l e   " " C : \ U s e r s \ B o s s \ I n s t a l l   w i n f e t c h . p s 1 " " " 

Set-Content
和第一个
Add-Content
都很好,所以这是最后一行的内容。我也尝试了
Out-File -Encoding utf8
Out-File -Append
,结果是一样的。

上面的输出是我在记事本中打开时的输出。如果我在 VS Code 中打开,情况会更糟;我在

sleep 5
之后看不到任何文字,只是一堆空值。

为什么前两行工作正常,然后第三行却是乱码,我应该如何构造东西才能获得有意义的输出?

编辑:相信我已经通过将

-Encoding utf8
添加到
Out-File -Append
行解决了问题。我在某处读到
-Append
-Encoding
开关不应一起使用,但似乎它们必须获得一致的输出。问题可以关闭,除非有人发现我发现的内容有错误。

powershell text utf-8
1个回答
0
投票

您问题中的代码没有解释症状,但您在评论中提到了真正的问题:

  • 如果您使用

    Out-File
    -Append
    附加到预先存在的文件,您必须显式地 将预先存在的内容的编码与
    -Encoding
    参数
    匹配,即您的情况中的
    -Encoding utf8

    • 在没有
      -Encoding
      参数的情况下,
      Out-File
      使用 其默认编码,即 Windows PowerShell 中的“Unicode”(UTF-16LE)(导致您的症状)和(无 BOM)UTF -8 在 PowerShell(核心)7+
  • 相比之下,在两个 PowerShell 版本中,

    Add-Content
    尝试匹配现有编码,但是假设在预先存在的内容中缺少 BOM,其编码方式因版本而异 :

    • Windows PowerShell:ANSI(相当于 -Encoding Default
    • PowerShell 7+:UTF-8

由于您正在运行

Windows PowerShell 并使用 -Encoding utf8

 最初创建文件,因此该文件 
有一个 BOM(有 no -Encoding
 参数允许创建 
BOM-less UTF- Windows PowerShell 中的 8 个文件 - 请参阅此答案了解背景信息和解决方法)。

由于 BOM 的存在,

Add-Content

 因此能够明确匹配现有编码。

© www.soinside.com 2019 - 2024. All rights reserved.