1

Which is the better way to read output of a PowerShell script using C++ application. Tried with below code but couldn't get the output. It's perfectly ok to execute the same PowerShell script from a console but wanted to get the output of the PowerShell script to use the same in the application.

system("start powershell.exe Set-ExecutionPolicy RemoteSigned \n");
system("start powershell.exe d:\\callPowerShell.ps1");
system("cls");
Nani
  • 1,148
  • 3
  • 20
  • 35

1 Answers1

0

The same problem also happens to me, and following is my workaround: redirect the output of powershell into a text file, and after the exe finished, read its output from the text file.

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());
}
keineahnung2345
  • 2,635
  • 4
  • 13
  • 28