gpt4 book ai didi

powershell - 使用 Utf8 字符存储来自 native 应用程序的标准输出

转载 作者:行者123 更新时间:2023-12-03 16:26:18 24 4
gpt4 key购买 nike

我正在尝试从我从 PowerShell 运行的 npm 中捕获标准输出。 Npm 下载丢失的包并输出适当的树。

它的样子:

enter image description here .

那是正确的输出。

当我尝试从 PowerShell 执行相同操作并捕获结果时,我无法获得相同的字符:

Captured via Tee-Object

我用的时候也是一样

  • gpm install | Tee-Object -FilePath
  • gpm install | Out-File -FilePath .. -Encoding Unicode # or Utf8
  • $a = gpm install

  • 当我将 cmd.exe 输出重定向到文件时,内容如下所示:
    enter image description here

    如何在 PowerShell 中正确捕获输出?

    最佳答案

    PowerShell 是一个基于对象的 shell,具有基于对象的管道,但对于 native 应用程序,管道是基于字节流的。因此,PowerShell 在从/向 native 应用程序传递数据时必须从/转换为字节流。即使将数据从一个 native 应用程序传送到另一个应用程序或将 native 应用程序的输出重定向到文件时,也会发生这种转换。

    当 PowerShell 从 native 应用程序接收数据时,它会将字节流解码为字符串,并按换行符拆分该字符串。将字节流解码为字符串 PowerShell 使用控制台的输出编码:[Console]::OutputEncoding .如果您知道您的应用程序使用不同的输出编码,您可以显式更改控制台的输出编码以匹配您的应用程序的:

    [Console]::OutputEncoding=[Text.Encoding]::UTF8

    当 PowerShell 将数据传递给 native 应用程序时,它会使用 $OutputEncoding 中指定的编码将对象转换为字符串。偏好变量。

    关于powershell - 使用 Utf8 字符存储来自 native 应用程序的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990850/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com