【问题标题】:Read PowerShell output from pipe with UTF-16 encoding使用 UTF-16 编码从管道读取 PowerShell 输出
【发布时间】:2018-07-19 22:08:59
【问题描述】:

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

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 编码输出。

PowerShell 有类似的东西吗?归根结底,我想将 powershell 的输出存储在 wchar_t 缓冲区中。

【问题讨论】:

标签: c powershell encoding


【解决方案1】:

遗憾的是,PowerShell 没有与 cmd.exe/U 等效的功能。

据我所知,控制输出编码的唯一方法是在 PowerShell 进程更改[console]::OutputEncoding,但我并不肯定这将适用于所有场景:

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

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

这是来自cmd.exe 命令行的示例:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 2012-03-13
    • 2014-09-07
    • 2019-05-23
    • 2012-03-16
    相关资源
    最近更新 更多