2

此方法使用 WMI 在远程计算机上创建进程

public void RunProcess(string processName, int timeoutInMinutes)
{
    ObjectGetOptions objectGetOptions = new ObjectGetOptions();
    ManagementPath managementPath = new ManagementPath("Win32_Process");
    ManagementClass processClass = new ManagementClass(m_managementScope, managementPath, objectGetOptions);

    ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
    inParams["CommandLine"] = processName;
    ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

    if (outParams != null)
    {
        string processID = outParams["processId"].ToString();
        WaitForProcessToFinish(processID, timeoutInMinutes);
    }
    else
    {
        throw new Exception("process was not created while tried to run it");
    }
}

虽然此方法获取 processID 并应查询 ID x 的进程是否已结束。由于我无法使用任何 WMI 浏览器执行 WQL(因为它是 EventWatcher 查询)。我需要帮助才能让它工作。

private void WaitForProcessToFinish(string processID, int timeoutInMinutes)
{
    const string wmiPollingInSeconds = "10";

    string queryString = string.Format("SELECT * FROM __InstanceOperationEvent WITHIN {0} WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Handle={1}", wmiPollingInSeconds, processID);
    WqlEventQuery wql = new WqlEventQuery(queryString);
    ManagementEventWatcher watcher = new ManagementEventWatcher {Query = wql, Scope = m_managementScope};

    int currentTimeoutInminutes = 0;
    while (timeoutInMinutes > currentTimeoutInminutes)
    {
        ManagementBaseObject mbOobj = watcher.WaitForNextEvent();
        if ((((ManagementBaseObject)mbOobj["TargetInstance"])["ProcessID"].ToString() == processID))
        {
            break;
        }
        watcher.Stop();
        throw new Exception(string.Format("couldn't find process {0} to get it's events",processID));
    }
    watcher.Stop();
}
4

1 回答 1

2

尝试改用__InstanceDeletionEventWMI 事件

string queryString = string.Format("SELECT * FROM __InstanceDeletionEvent WITHIN {0} WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Handle={1}", wmiPollingInSeconds, processID);
于 2012-08-09T16:43:07.953 回答