树在 Cmd 上看起来与在 Powershell 上不同

Tree looks different on Cmd than it does on Powershell

为什么 tree 命令在 Powershell 上看起来与在 Cmd 上看起来不同。

我相信这是因为它是 PowerShell 在后台运行 cmd 然后将输出通过管道传输到 Write-Host 的命令之一,类似于 pingipconfig

  • 问题只发生在 PowerShell ISE,其中来自外部程序的输出,例如 tree.com 没有直接传递到控制台。

    • 考虑从 PowerShell ISE 迁移,因为它 no longer actively developed and (bottom section), notably the inability to run PowerShell [Core] 6+, where all future effort will go. The editor that offers the best PowerShell development experience, across platforms, is Visual Studio Code, combined with its PowerShell extension 正在积极开发中。
  • 要修复它,您必须(暂时)更改 [Console]::OutputEncoding 以匹配您系统的活动 OEM 遗留代码页,因为那是字符编码 tree.com 使用:

# Switch the encoding that PowerShell expects external programs to use
# to the active OEM code page.
[Console]::OutputEncoding = [System.Text.Encoding]::GetEncoding(
  [cultureinfo]::CurrentCulture.TextInfo.OEMCodePage
)

# tree.com now produces the expected output in the ISE
tree

注:

  • 即使在常规控制台 window / Windows 终端 window 和 Visual Studio 代码 [Console]::OutputEncoding 可以发挥作用,但只有当您捕获或重定向外部程序的输出(例如,$treeOutput = treetree | ...).

    • 如上所述,对于直接显示输出,这 不是 所必需的 - 除了在 ISE 中,[Console]::OutputEncoding 即使在那时也很重要,默认为系统的活动 ANSI 遗留代码页。
  • 要让 PowerShell 在捕获或重定向外部程序时正确解释它的输出,[Console]::OutputEncoding 必须与该程序使用的实际编码相匹配

因此,如果您想要捕获或重定向 tree.coms 输出,您可能设置 [Console]::OutputEncoding:

简而言之,除非 [Console]::OutputEncoding.CodePage[cultureinfo]::CurrentCulture.TextInfo.OEMCodePage 报告的代码页编号匹配 - 例如,在美国英语系统上 437 - 设置 [Console]::OutputEncoding 需要

  • 控制台windowsWindows终端windows这个通常 不是 必需的(从 PowerShell 7.0 开始)- 仅当您明确将活动代码页更改为 UTF-8 时才有必要,例如 - 请参阅 ;请注意,随着时间的推移,UTF-8 可能会成为默认值。

  • Visual Studio代码中,然而,默认情况下必需的,因为在PowerShell中集成控制台 [Console]::OutputEncoding 默认为 UTF-8(代码页 65001)。