简体   繁体   English

C++ Powershell 没有正确执行命令?

[英]C++ Powershell not executing command properly?

So, I have a quick bit of code that should give me the drive serials that are currently installed on the system, however, when I run this, powershell gets an error.所以,我有一小段代码应该给我当前安装在系统上的驱动器序列,但是,当我运行它时,powershell 得到一个错误。 I'm not entirely sure what's wrong here, as when I type the command on powershell it works fine.我不完全确定这里出了什么问题,因为当我在 powershell 上键入命令时它工作正常。 Here is some of the code:这是一些代码:

std::string exec(const char* cmd) {
    std::array<char, 128> buffer;
    std::string result;
    std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
    if (!pipe) throw std::runtime_error("_popen() failed!");
    while (!feof(pipe.get())) {
        if (fgets(buffer.data(), 128, pipe.get()) != NULL)
            result += buffer.data();
    }
    return result;
};

Later I call this:后来我称之为:

std::string test = exec("powershell -ExecutionPolicy Bypass get-ciminstance Win32_LogicalDisk | % VolumeSerialNumber");

If this works correctly, I should have a string with multiple serial numbers on it (as I have multiple drives), however I don't.如果这工作正常,我应该有一个带有多个序列号的字符串(因为我有多个驱动器),但我没有。 I get this powershell error that is printed into my console.我收到这个 powershell 错误,它打印到我的控制台中。

'%' is not recognized as an internal or external command,
operable program or batch file.

Anyone have any ideas on how to fix this?有人对如何解决这个问题有任何想法吗? I tried adding a \ before the % but that didn't work either.我尝试在 % 之前添加一个 \ ,但这也不起作用。 Any help is greatly appreciated!任何帮助是极大的赞赏!

_popen spawns cmd.exe to run your command. _popen生成cmd.exe以运行您的命令。

The _popen function creates a pipe. _popen function 创建一个 pipe。 It then asynchronously executes a spawned copy of the command processor, and uses command as the command line.然后它异步执行命令处理器的衍生副本,并使用命令作为命令行。

Thus the |因此| is being interpreted by cmd, which tries to run % as a command.正在由 cmd 解释,它试图将%作为命令运行。

Thus the output coming out of cmd :因此来自 cmd 的cmd

'%' is not recognized as an internal or external command, operable program or batch file. '%' 不是内部或外部命令、可运行程序或批处理文件。

To fix it, I believe quoting the powershell program in the command should be enough.要修复它,我相信在命令中引用 powershell 程序就足够了。

exec("powershell -ExecutionPolicy Bypass \"get-ciminstance Win32_LogicalDisk | % VolumeSerialNumber\"");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM