![默认 PowerShell 发射的是 UTF-8 而不是 UTF-16?](https://linux22.com/image/1708875/%E9%BB%98%E8%AE%A4%20PowerShell%20%E5%8F%91%E5%B0%84%E7%9A%84%E6%98%AF%20UTF-8%20%E8%80%8C%E4%B8%8D%E6%98%AF%20UTF-16%EF%BC%9F.png)
默认情况下,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 文档了解详情。