请看此demo
#include <iostream>
#include <Windows.h>
#include <vector>
#include <string>
using namespace std;
//#include <ostringstream>
std::string executeCommand(const std::string& command) {
std::string result;
HANDLE g_hChildStd_OUT_Rd = NULL;
HANDLE g_hChildStd_OUT_Wr = NULL;
HANDLE g_hChildStd_ERR_Rd = NULL;
HANDLE g_hChildStd_ERR_Wr = NULL;
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)) {
cerr << "Error creating pipe for stdout." << endl;
return result;
}
if (!CreatePipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &saAttr, 0)) {
cerr << "Error creating pipe for stderr." << endl;
CloseHandle(g_hChildStd_OUT_Rd);
CloseHandle(g_hChildStd_OUT_Wr);
return result;
}
STARTUPINFOA si;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
si.hStdError = g_hChildStd_ERR_Wr;
si.hStdOutput = g_hChildStd_OUT_Wr;
si.dwFlags |= STARTF_USESTDHANDLES;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
string cmdToExecute = "powershell.exe -Command \"" + command + "\"";
if (!CreateProcessA(NULL, const_cast<char*>(cmdToExecute.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
cerr << "Error creating process. Error code: " << GetLastError() << endl;
CloseHandle(g_hChildStd_OUT_Rd);
CloseHandle(g_hChildStd_OUT_Wr);
CloseHandle(g_hChildStd_ERR_Rd);
CloseHandle(g_hChildStd_ERR_Wr);
return result;
}
CloseHandle(g_hChildStd_OUT_Wr);
CloseHandle(g_hChildStd_ERR_Wr);
const DWORD bufferSize = 4096;
char buffer[bufferSize];
DWORD bytesRead;
bool bSuccess = true;
vector<char> outputData;
do {
bSuccess = ReadFile(g_hChildStd_OUT_Rd, buffer, bufferSize, &bytesRead, NULL);
if (bSuccess && bytesRead > 0) {
outputData.insert(outputData.end(), buffer, buffer + bytesRead);
}
else {
break;
}
} while (true);
bSuccess = ReadFile(g_hChildStd_ERR_Rd, buffer, bufferSize, &bytesRead, NULL);
if (bSuccess && bytesRead > 0) {
outputData.insert(outputData.end(), buffer, buffer + bytesRead);
}
CloseHandle(g_hChildStd_OUT_Rd);
CloseHandle(g_hChildStd_ERR_Rd);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
if (!outputData.empty()) {
result.assign(outputData.begin(), outputData.end());
}
return result;
}
这就是关键函数,此函数可将输入的command应用输入到powershell;
然后将结果记录到result返回
在函数外面仅需一个string对象即可全部接受;
具体deom自行测试吧