使用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
.