c++ Powershell不能正确执行命令?



所以,我有一个简短的代码,它应该给我当前安装在系统上的驱动器序列,但是,当我运行它时,powershell得到一个错误。我不完全确定这里出了什么问题,因为当我在powershell上输入命令时,它工作得很好。下面是一些代码:

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;
};

之后我称之为:

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

如果这正常工作,我应该有一个字符串上有多个序列号(因为我有多个驱动器),但我没有。我得到这个powershell错误,打印到我的控制台。

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

谁对如何解决这个问题有任何想法?我试着在%之前加一个,但那也不起作用。任何帮助都非常感谢!

_popen生成cmd.exe来运行您的命令。

_popen函数创建一个管道。然后,它异步执行命令处理器的派生副本,并使用command作为命令行。

因此|被cmd解释,它试图将%作为命令运行。

因此cmd输出:

'%'无法识别为内部或外部命令,可操作程序或批处理文件。

为了解决这个问题,我认为在命令中引用powershell程序应该足够了。

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

最新更新