使用Utf8字符存储来自本机应用程序的标准输出 [英] Storing standard output from native app with Utf8 characters

查看:257
本文介绍了使用Utf8字符存储来自本机应用程序的标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图捕获从npm运行的PowerShell的标准输出。

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做同样的事情并捕获结果, m无法获得相同的字符:

When I try to do the same from PowerShell and capture the result, I'm not able to get the same characters:

使用


  • gpm install | Tee-Object -FilePath

  • gpm install | Out-File -FilePath ..-编码Unicode#或Utf8

  • $ a = gpm install / li>
  • gpm install | Tee-Object -FilePath or
  • gpm install | 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 object based shell, and have object based pipeline, but for native application pipeline is byte stream based. So PowerShell have to convert from/to byte stream when pass data from/to native application. This conversion happens even when, you pipe data from one native application to another native application, or redirect native application output to file.

当PowerShell从本机应用程序传递数据时,它会发生这种转换,即使您将数据从一个本机应用程序管道传输到另一个本机应用程序,将字节流解码为字符串,并用新行字符拆分字符串。对于解码字节流到字符串PowerShell使用控制台的输出编码: [Console] :: OutputEncoding 。如果您知道您的应用程序对输出使用不同的编码,您可以显式更改控制台的输出编码以匹配应用程序的编码:

When PowerShell pass data from native application, it decode byte stream as string, and split string by new line character. For decoding byte stream to string PowerShell use output encoding of console: [Console]::OutputEncoding. If you know that your application use different encoding for output, than you can explicitly change output encoding of console to match encoding of your application:

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



<到本机应用程序,它将对象转换为字符串,并使用 $ OutputEncoding 偏好变量的编码对该字符串进行编码。

When PowerShell pass data to native application, it convert objects to strings and encode that strings using encoding from $OutputEncoding preference variable.

这篇关于使用Utf8字符存储来自本机应用程序的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆