c++ - 如何使用 C++ 获取 powershell 命令的输出?

标签 c++ visual-c++ powershell cmd console

我在 powershell 的帮助下实现了网络统计程序 scrpit .该程序运行成功,并为我提供了完美的输出。下面是我的程序。

int main(int argc, char *argv[])
{
       string strPath = "C:\\Get-NetworkStatistics.ps1";
      char str[50] =  "C:\\Get-NetworkStatistics.ps1";

       char command[500];

//access function:
       //The function returns 0 if the file has the given mode.
       //The function returns –1 if the named file does not exist or does not have the given mode
       if(access(strPath.c_str(),0) == 0)
       {


_snprintf(command, sizeof(command), "Start Powershell.exe -noexit Set -executionpolicy;.'%s';Get-NetworkStatistics",str);
system(command);



       }

       else 
       {
              system("cls");
              cout << "File is not exist";
              system("pause");
        }
return 0;
}

! here is the output of above program

如您所见,输出在 powershell 窗口中。我想获取 powershell 输出的所有这些数据,并希望在控制台中显示它。怎么可能?

请帮帮我..

最佳答案

除非您需要在信息可用时实时显示信息,否则只需将其重定向到一个文件,然后从 C++ 读取该文件即可。

由于 netstat 在 Windows XP SP 2 或附近被切除,我可以理解使用 Powershell。

可能 netstat 将满足您的需求,这样您就不必处理任何复杂的问题。


顺便说一句,我建议使用脚本语言来编写脚本任务。当然,默认情况下禁用 Powershell 脚本会很复杂,否则会指示使用 Powershell 脚本工具。但是例如在这种情况下,[cmd.exe] 批处理文件比从 C++ 执行它的工作更自然。

可从 JScript 和 VBScript 获得的 Windows 脚本宿主 shell 对象提供了通过输出抓取来执行进程的功能。

有一个小问题,您必须轮询输出,但我认为它仍然比在 C/C++ API 级别执行此操作更容易。

关于c++ - 如何使用 C++ 获取 powershell 命令的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24180653/

相关文章:

c++ - 新添加到现有项目中的命令按钮的VC6 MFC错误

python - 在python中读取txt文件

powershell - 将变量传递给 Start-Job

powershell - 将多个域添加到 azure 网站

c++ - 混淆条件的评估和 for 循环的步骤

C++编译错误: syntax error : '<cv-qualifer>'

windows - 如何设置MDI客户端的大小和位置?

c++ - CRT 未检测到 DLL 中的内存泄漏

c++ - 从 Sprite SFML vector 中绘制

c++ - 聚合内标量的大括号初始化