1

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

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

1 回答 1

0

同样的问题也发生在我身上,以下是我的解决方法:将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());
}
于 2020-08-20T08:05:29.250 回答