c++ - 从 C++ 应用程序获取 PowerShell 脚本输出
问题描述
这是使用 C++ 应用程序读取 PowerShell 脚本输出的更好方法。尝试使用以下代码,但无法获得输出。从控制台执行相同的 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());
}
推荐阅读
- c# - 在变量中有一个 Json 数据,并希望在 asp.net 中以表格形式显示该数据
- c++ - TBB:可以获得线程 ID 吗?
- bash - bash:g ++:找不到命令
- javascript - 如何使用 NestJS 正确设置序列化?
- c# - 如何检索元素键值?
- amazon-web-services - 是否可以将 S3 存储桶日志用作面向隐私/基本分析的黑客攻击?
- vue.js - 在 vuejs 中重用具有多个相同类型组件的文本
- python-3.x - 从 Lambda 的 /tmp 文件夹中读取 csv 文件,过滤并上传到 s3
- java - 在 Java 中控制剪辑音量 -> FloatControl Volume 什么都不做
- c++ - 如何更新 Node.js 原生插件以使用新 API?