默认 PowerShell 发出 UTF-8 而不是 UTF-16?

Ben*_*ack 34 powershell redirection character-encoding

默认情况下,Windows 中的 PowerShell 似乎输出 UTF-16(例如,如果我执行简单的echo hello > hi.txthi.txt则以 UTF-16 结束)。我知道我可以通过代替执行将其强制为我想要的文本编码echo hello | out-file -encoding utf8 hi.txt,但我希望它只是我使用重定向运算符时的默认值。有没有办法实现这一目标?

小智 23

在 System.Management.Automation 程序集(又名“Microsoft Windows PowerShell 引擎核心程序集”)上使用 .NET 反编译器显示以下代码片段:

// class: System.Management.Automation.RedirectionNode
private PipelineProcessor BuildRedirectionPipeline(string path, ExecutionContext context)
{
    CommandProcessorBase commandProcessorBase = context.CreateCommand("out-file");
    commandProcessorBase.AddParameter("-encoding", "unicode");
    if (this.Appending)
    {
        commandProcessorBase.AddParameter("-append", true);
    }
    commandProcessorBase.AddParameter("-filepath", path);
    ...
Run Code Online (Sandbox Code Playgroud)

所以,对我来说,它看起来很硬编码。

仅供参考,这是在安装了 PowerShell 2.0 的 Windows 7 Enterprise x64 系统上。

  • 不幸的是,仍然在 Windows 10 上的 PowerShell 5 中进行了硬编码:`CommandParameterInternal.CreateParameterWithArgument(PositionUtilities.EmptyExtent, "Encoding", "-Encoding:", PositionUtilities.EmptyExtent, "Unicode", false, false);` (5认同)