【问题标题】:Get PowerShell script output from C++ App从 C++ 应用程序获取 PowerShell 脚本输出
【发布时间】:2020-10-09 16:20:39
【问题描述】:

哪种方法是使用 C++ 应用程序读取 PowerShell 脚本输出的更好方法。尝试使用以下代码,但无法获得输出。从控制台执行相同的 PowerShell 脚本是完全可以的,但希望获得 PowerShell 脚本的输出以在应用程序中使用相同的脚本。

system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n");
system("start powershell.exe d:\\callPowerShell.ps1");
system("cls");

【问题讨论】:

    标签: c++ powershell console remote-execution


    【解决方案1】:

    同样的问题也发生在我身上,以下是我的解决方法:将powershell的输出重定向到一个文本文件中,exe完成后,从文本文件中读取其输出。

    std::string psfilename = "d:\\test.ps1";
    std::string resfilename = "d:\\res.txt";
    std::ofstream psfile;
    psfile.open(psfilename);
    
    //redirect the output of powershell into a text file
    std::string powershell = "ls > " + resfilename + "\n";
    psfile << powershell << std::endl;
    psfile.close();
    
    system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n");
    //"start": run in background
    //system((std::string("start powershell.exe ") + psfilename).c_str());
    system((std::string("powershell.exe ") + psfilename).c_str());
    system("cls");
    
    remove(psfilename.c_str());
    
    //after the exe finished, read the result from that txt file
    std::ifstream resfile(resfilename);
    std::string line;
    if (resfile.is_open()) {
        std::cout << "result file opened" << std::endl;
        while (getline(resfile, line)) {
            std::cout << line << std::endl;
        }
        resfile.close();
        remove(resfilename.c_str());
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-23
      • 2018-06-09
      • 2015-07-19
      • 2013-01-08
      • 2021-03-14
      • 2016-03-22
      • 2011-11-16
      • 1970-01-01
      • 2011-10-24
      相关资源
      最近更新 更多