Reputation: 1176
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");
Upvotes: 1
Views: 2632
Reputation: 2701
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());
}
Upvotes: 0