有时候,我们需要执行 PowerShell 命令来取得一些信息,通过下面的代码能在 VC 中执行命令并且获得返回值:
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
// 描述:execmd函数执行命令,并将结果存储到result字符串数组中
// 参数:cmd表示要执行的命令, result是执行的结果存储的字符串数组
// 函数执行成功返回1,失败返回0
#pragma warning(disable:4996)
int execmd(char* cmd, char* result) {
char buffer[128]; //定义缓冲区
FILE* pipe = _popen(cmd, "r"); //打开管道,并执行命令
if (!pipe)
return 0; //返回0表示运行失败
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe)) { //将管道输出到result中
strcat(result, buffer);
}
}
_pclose(pipe); //关闭管道
return 1; //返回1表示运行成功
}
int main(void)
{
char res[2048] = { 0 };
execmd("powershell $psversiontable", res);
printf("Result [%s]\r\n",res);
getchar();
}
下面是运行结果,可以看到二者完全相同。

特别注意:如果遇到下面这样的错误提示,那么需要扩大 res[] 。
Run-Time Check Failure #2 – Stack around the variable ‘a’ was corrupted.
参考:
1.https://www.cnblogs.com/htj10/p/13830785.html VC执行Cmd命令,并获取结果
2.https://blog.csdn.net/weixin_42395980/article/details/112123690 c++ 调用 powershell_十九,Powershell基础入门及常见用法(一)
很有用。解决了我的问题,感谢博主的分享。