【问题标题】:Tree looks different on Cmd than it does on Powershell树在 Cmd 上的外观与在 Powershell 上的不同
【发布时间】:2020-04-29 22:51:16
【问题描述】:

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

【问题讨论】:

  • 尝试其他字体。以康索拉为例。
  • 使用/a 选项来使用文本字符而不是图形字符。原因是 PoSh 控制台不支持相同的字符集,除非你找到一种方法来告诉它这样做……而我目前找不到任何方法。
  • PS 使用 ANSI 或 Unicode,CMD 使用 OEM(也称为 DOS)
  • @Olaf 这是字符编码问题,所以选择不同的字体无济于事。
  • @Lee_Dailey 请注意,该问题仅影响 ISE;将 [Console]::OutputEncoding 设置为 OEM 代码页可以修复它;详情见我的回答。

标签: powershell cmd powershell-ise


【解决方案1】:
  • 问题仅出现在 PowerShellISE 中,其中来自外部程序(例如 tree.com 的输出不会直接传递到控制台。

  • 要修复它,您必须(临时)更改 [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

注意:

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

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

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

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

  • 控制台窗口Windows 终端窗口 中,这通常不需要(从 PowerShell 7.0 开始) - 仅需要例如,如果您已将活动代码页显式更改为 UTF-8,请参见 this answer;请注意,随着时间的推移,UTF-8 可能会成为默认设置。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • tree.com 是一个外部可执行文件,PowerShell 直接调用它——cmd.exe 不参与。在控制台窗口和 Visual Studio Code 的 PowerShell 集成终端中,来自外部程序的输出传递到控制台(除非捕获或重定向)。相比之下,在 ISE 中,输出首先在内部被捕获和解码,然后打印到显示器上(尽管我怀疑是否涉及实际的 Write-Host 调用)。
    猜你喜欢
    • 1970-01-01
    • 2023-04-04
    • 2015-01-13
    • 1970-01-01
    • 2021-06-28
    • 2021-07-18
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多