使用 Utf8 字符存储本机应用程序的标准输出 [英] Storing standard output from native app with Utf8 characters
问题描述
我正在尝试从我从 PowerShell 运行的 npm 捕获标准输出.npm 下载丢失的包并输出适当的树.
I'm trying to capture standard output from npm that I run from PowerShell. Npm downloads packages that are missing and outputs appropriate tree.
它的样子:
.
这是正确的输出.
当我尝试从 PowerShell 执行相同操作并捕获结果时,我无法获得相同的字符:
When I try to do the same from PowerShell and capture the result, I'm not able to get the same characters:
我用的时候也是这样
gpm 安装 |Tee-Object -FilePath
或gpm 安装 |Out-File -FilePath .. -Encoding Unicode # or Utf8
$a = gpm install
当我将 cmd.exe 输出重定向到文件时,内容如下所示:
When I redircect in cmd.exe output to a file, the content looks like this:
如何在 PowerShell 中正确捕获输出?
How can I capture the output correctly in PowerShell?
推荐答案
PowerShell 是一个基于对象的 shell,具有基于对象的管道,但对于本机应用程序,管道是基于字节流的.因此,当 PowerShell 从/向本机应用程序传递数据时,它必须从/向字节流进行转换.即使您将数据从一个本地应用程序传送到另一个应用程序或将本地应用程序的输出重定向到文件时,也会发生这种转换.
PowerShell is an object-based shell with an object-based pipeline, but for native applications the pipeline is byte-stream-based. So PowerShell has to convert from/to a byte stream when it passes data from/to a native application. This conversion happens even when you pipe data from one native application to another or redirect a native application's output to a file.
当 PowerShell 从本机应用程序接收数据时,它会将字节流解码为字符串,并按换行符拆分该字符串.为了将字节流解码为字符串,PowerShell 使用控制台的输出编码:[Console]::OutputEncoding
.如果您知道您的应用程序使用不同的输出编码,您可以显式更改控制台的输出编码以匹配您的应用程序:
When PowerShell receives data from a native application, it decodes the byte stream as a string, and splits that string by the newline character. For decoding byte streams to strings PowerShell uses the console's output encoding: [Console]::OutputEncoding
. If you know that your application use a different output encoding, you can explicitly change the console's output encoding to match your application's:
[Console]::OutputEncoding=[Text.Encoding]::UTF8
当 PowerShell 将数据传递给本机应用程序时,它会使用 $OutputEncoding
首选项变量中指定的编码将对象转换为字符串.
When PowerShell passes data to a native application, it convert objects to strings using the encoding specified in the $OutputEncoding
preference variable.
这篇关于使用 Utf8 字符存储本机应用程序的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!