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

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

默认情况下,Windows 中的 PowerShell 似乎输出 UTF-16(例如,如果我执行简单的echo hello > hi.txt,则hi.txt最终结果为 UTF-16)。我知道我可以通过执行 来强制将其强制为所需的文本编码echo hello | out-file -encoding utf8 hi.txt,但我希望在使用重定向运算符时这只是默认设置。有什么办法可以实现吗?

答案1

在 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);
    ...

因此,对我来说它看起来相当硬编码。

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

答案2

不确定这是否能满足您的要求,但您可以尝试设置上述环境变量这里

$OutputEncoding = New-Object -typename System.Text.UTF8Encoding

答案3

您需要更改重定向运算符(> 和 >>)的默认编码。Out-File当您使用这些运算符时,cmdlet 会在后台使用。

$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'

Powershell 文档了解详情。

相关内容