从C++应用获取PowerShell脚本输出

Get PowerShell script output from C++ App

本文关键字:脚本 输出 PowerShell 获取 C++ 应用      更新时间:2023-10-16

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

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

同样的问题也发生在我身上,以下是我的解决方法:将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());
}