繁体   English   中英

从 C++ 应用程序获取 PowerShell 脚本 output

[英]Get PowerShell script output from C++ App

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

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

同样的问题也发生在我身上,以下是我的解决方法:将 powershell 的 output 重定向到文本文件中,并在 exe 完成后,从文本文件中读取其 Z78E6221F6393D1356681DB398F14CED6。

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());
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM