Powershell 中其他程序的文本输出在字符之间包含不需要的空格

问题描述 投票:0回答:1

我想在 Powershell 中使用其他程序的(文本)输出,但我一直得到这种奇怪的格式,每个字符之间都有不需要的空格。

例如跑步时:

&"C:\Program Files\Common Files\McAfee\SystemCore\aacinfo.exe" report

它产生如下输出:

Subscribing for reports, press any key to stop...


Reporting on point-product 12dd49a3-c20f-4636-b638-fc9ce8c76735
Waiting for events for point-product ProductTracker...

Reporting on point-product 4562a25a-895d-4e20-bb47-7317801f0108
Waiting for events for point-product ProductTracker...

如此如此...这是一个连续的流,直到程序停止。

当我尝试将其保存到文件中时:

& "C:\Program Files\Common Files\McAfee\SystemCore\aacinfo.exe" report | out-file -encoding utf8 C:\temp\output.log

文件内容如下所示:

S u b s c r i b i n g   f o r   r e p o r t s ,   p r e s s   a n y   k e y   t o   s t o p . . . 
 
 
 
 
 
 R e p o r t i n g   o n   p o i n t - p r o d u c t   1 2 d d 4 9 a 3 - c 2 0 f - 4 6 3 6 - b 6 3 8 - f c 9 c e 8 c 7 6 7 3 5 
 
 W a i t i n g   f o r   e v e n t s   f o r   p o i n t - p r o d u c t   P r o d u c t T r a c k e r . . . 
 
 
 
 R e p o r t i n g   o n   p o i n t - p r o d u c t   4 5 6 2 a 2 5 a - 8 9 5 d - 4 e 2 0 - b b 4 7 - 7 3 1 7 8 0 1 f 0 1 0 8 
 
 W a i t i n g   f o r   e v e n t s   f o r   p o i n t - p r o d u c t   P r o d u c t T r a c k e r . . . 

这是为什么以及如何避免字符之间的所有额外空格?

powershell format output
1个回答
0
投票

看起来

aacinfo.exe
意外地输出 UTF-16LE 编码文本,而不是使用当前控制台代码页指定的字符编码(如
chcp
的输出所示)。

因为 PowerShell 期望后者,所以它误解了

aacinfo.exe
的输出,这解释了您的症状。

解决方案是临时将

[Console]::OutputEncoding
设置为 UTF-16LE,这指示 PowerShell 使用该编码来解码
aacinfo.exe
的输出:

$prev = [Console]::OutputEncoding
[Console]::OutputEncoding = [System.Text.Encoding]::Unicode

& 'C:\Program Files\Common Files\McAfee\SystemCore\aacinfo.exe' report | 
  Out-File -Encoding utf8 C:\temp\output.log

[Console]::OutputEncoding = $prev
© www.soinside.com 2019 - 2024. All rights reserved.