使用UTF-16编码从管道读取PowerShell输出 [英] Read PowerShell output from pipe with UTF-16 encoding

查看:137
本文介绍了使用UTF-16编码从管道读取PowerShell输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前正在尝试通过调用 CreateProcess()从管道读取PowerShell的输出。

I'm currently trying to read the output of PowerShell from a pipe, by calling CreateProcess().

startInfo.cb = sizeof(STARTUPINFOW);
startInfo.hStdError = pipes->hErrWrite;
startInfo.hStdOutput = pipes->hOutWrite;
startInfo.hStdInput = pipes->hInRead;
startInfo.dwFlags = STARTF_USESTDHANDLES

BOOL success = CreateProcessW(
    L"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
    NULL,
    NULL,
    NULL,
    TRUE,
    0,
    NULL,
    NULL,
    &startInfo,
    &procInfo
);

一切正常,但是PowerShell的输出具有不同的编码。
我已经做了与CMD相同的步骤。幸运的是,CMD可以选择使用 / U 参数启动它,该参数包含了UTF-16的输出。

Everything works fine, but the output of PowerShell has a different encoding.
I already did the same procedure with CMD. Luckily, CMD has the option to start it with the /U parameter, which encododed the output in UTF-16.

PowerShell有什么类似之处吗?最终,我想将powershell的输出存储在 wchar_t 缓冲区中。

Is there something similiar for PowerShell? At the end of the day, I'd like to store the output of powershell in a wchar_t buffer.

推荐答案

PowerShell没有等效于 cmd.exe / U

PowerShell has no equivalent to cmd.exe's /U, unfortunately.

控制我所知道的输出编码的唯一方法是更改​​ [console] :: OutputEncoding within 在PowerShell进程中进行,但是我不太肯定这种方法在所有情况下都适用:

The only way to control the output encoding that I know of is to change [console]::OutputEncoding from within the PowerShell process, but I'm not positive that will work in all scenarios:

这是您要执行的一部分PowerShell代码需要在产生任何输出之前执行 (您必须将其作为命令的一部分通过 -Command 参数传递):

Here's the piece of PowerShell code you'd need to execute before producing any output (you'd have to pass that as part of the command to execute via the -Command parameter):

[console]::outputencoding=[text.encoding]::unicode

下面是 cmd.exe 命令行的示例:

powershell -command "[console]::outputencoding=[text.encoding]::unicode; 'Motörhead'" > out.txt

这将产生UTF16-LE编码的 out.txt 文件,其中包含字符串Motörhead

This would produce a UTF16-LE-encoded out.txt file containing the string Motörhead.

这篇关于使用UTF-16编码从管道读取PowerShell输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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