输入编码:接受UTF-8

时间:2010-05-25 07:47:40

标签: encoding powershell

我需要在PowerShell下输出本机应用程序。问题是,输出使用UTF-8(无BOM)编码,PowerShell无法识别,只是将这些时髦的UTF字符直接转换为Unicode。

我发现PowerShell有$OutputEncoding变量,但它似乎不会影响输入数据。

好的'iconv也没有任何帮助,因为这个不必要的UTF8-as-if-ASCII =>在下一个管道成员获取数据之前进行Unicode转换。

3 个答案:

答案 0 :(得分:12)

我现在看到下面的程序问题(stdout.cpp - cl stdout.cpp):

#include <stdio.h>

void main()
{
    char bytes[] = { 0x41, 0x53, 0x43, 0x49, 
                     0x49, 0x20, 0x6F, 0x75, 
                     0x74, 0x70, 0x75, 0x74,
                     0xE1, 0xBE, 0xB9};

    for (int i = 0; i < 15; i++)
    {
        printf("%c", bytes[i]);
    }                
}

通过| Out-File -enc UTF8 foo.txt运行,给出了胡言乱语:

PS> fhex foo.txt

Address:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F ASCII
-------- ----------------------------------------------- ----------------
00000000 EF BB BF 41 53 43 49 49 20 6F 75 74 70 75 74 0D ...ASCII output.
00000010 9F E2 95 9B E2 95 A3 0D 0A                      .........

请注意,fhex是PSCX实用程序。

更新:想出如何让它发挥作用:

$enc = [Console]::OutputEncoding
[Console]::OutputEncoding = [text.encoding]::utf8
.\stdout.exe | out-file fubar3.txt -enc utf8
fhex .\fubar3.txt

Address:  0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F ASCII
-------- ----------------------------------------------- ----------------
00000000 EF BB BF 41 53 43 49 49 20 6F 75 74 70 75 74 E1 ...ASCII output.
00000010 BE B9 0D 0A                                     ....

[Console]::OutputEncoding = $enc

答案 1 :(得分:0)

请务必执行“chcp 65001”(修改powershell.exe的字体后) 该命令适用于PSISE。

答案 2 :(得分:-2)

如果您的目标是在PowerShell中处理来自本机命令的数据,则可以尝试

./program-that-outputs-utf8 > temp.txt
get-content temp.txt -Encoding utf8 | (do_whatever)