Получение вывода сценария PowerShell из приложения C ++ - PullRequest
1 голос
/ 19 июня 2020

Какой способ лучше читать вывод сценария PowerShell с помощью приложения C ++. Пытался с кодом ниже, но не смог получить результат. Совершенно нормально выполнить тот же сценарий PowerShell из консоли, но хотелось получить вывод сценария PowerShell для использования его в приложении.

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

1 Ответ

0 голосов
/ 20 августа 2020

Та же проблема случается и со мной, и вот мой обходной путь: перенаправить вывод 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());
}
...