使用 UTF-16 编码从管道读取 PowerShell 输出

2023-12-24

我目前正在尝试通过调用从管道读取 PowerShell 的输出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 编码输出。

PowerShell 有类似的东西吗?在一天结束时,我想将 powershell 的输出存储在wchar_t buffer.


PowerShell 没有等效项cmd.exe's /U, 很遗憾。

据我所知,控制输出编码的唯一方法是更改[console]::OutputEncoding from withinPowerShell 进程,但我不确定它适用于所有情况:

这是您需要执行的一段 PowerShell 代码before产生任何输出(您必须将其作为命令的一部分传递以通过-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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 UTF-16 编码从管道读取 PowerShell 输出 的相关文章

随机推荐