簡體   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