将命令输出到windows下的powershell,并且获取其输出

请看此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自行测试吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值