c++执行powershell命令并获取返回数据

5 篇文章 1 订阅

编程过程中我们可能需要用到powershell命令辅助我们快速实现某些功能,下面的代码将运行cmd命令并且获取返回数据


#include <string>
#include <vector>
#include <shlobj.h>
 
#define RunCmdWaitTimeout (20 * 1000)

std::string RunPowerShellWaitReturn(const std::string& strCmd, int dwMilliseconds = RunCmdWaitTimeout)
{
    std::string strNewCmd = "powershell.exe -Command \"" + strCmd + "\"";
   
    SECURITY_ATTRIBUTES sa = { 0 };
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;
    STARTUPINFOA si = { 0 };
    PROCESS_INFORMATION pi = { 0 };
    std::string tempCmd;
    LPSTR cmdLine = NULL;
    std::vector<char> buffer(4096);
    DWORD bytesRead = 0;
    std::string output;

    HANDLE hRead = NULL, hWrite = NULL;
    if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
        printf("CreatePipe failed (%d).\n", GetLastError());
        goto Exit0;
    }

    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    ZeroMemory(&pi, sizeof(pi));

    si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
    si.wShowWindow = SW_HIDE; // 隐藏窗口
    si.hStdOutput = hWrite;
    si.hStdError = hWrite;

    tempCmd = std::string(strNewCmd.begin(), strNewCmd.end());
    cmdLine = &tempCmd[0];
    if (!CreateProcessA(NULL, cmdLine, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) {
        printf("CreateProcess failed (%d).\n", GetLastError());
        goto Exit0;
    }

    if (hWrite)
    {
        CloseHandle(hWrite);
        hWrite = NULL;
    }

    // 读取子进程的输出
    while (true) {
        if (!ReadFile(hRead, &buffer[0], buffer.size(), &bytesRead, NULL) || bytesRead == 0) {
            if (GetLastError() == ERROR_BROKEN_PIPE)
                break;
            else
                printf("ReadFile failed (%d).\n", GetLastError());
        }
        output.append(&buffer[0], bytesRead);
    }

    // 等待子进程退出
    if (pi.hProcess)
        WaitForSingleObject(pi.hProcess, dwMilliseconds);

Exit0:
    // 关闭进程和线程句柄
    if (pi.hThread)
        CloseHandle(pi.hThread);

    if (pi.hProcess)
        CloseHandle(pi.hProcess);

    if (hRead)
        CloseHandle(hRead);

    if (hWrite)
        CloseHandle(hWrite);

    return output;
}

int mian()
{
    auto strResult= RunPowerShellWaitReturn("ping -n 1 127.0.0.1");
}

其中RunCmdWaitTimeout是执行命令默认的等待时间

直接调用RunPowerShellWaitReturn我们可以看到返回值strResult值如下:

正在 Ping 127.0.0.1 具有 32 字节的数据:
来自 127.0.0.1 的回复: 字节=32 时间<1ms TTL=128
 
127.0.0.1 的 Ping 统计信息:
    数据包: 已发送 = 1,已接收 = 1,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 0ms,平均 = 0ms

如果想执行cmd命令可以查看另外一篇文章

c++执行cmd命令并获取返回数据-CSDN博客

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那一片海

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值