此方法使用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();
}
答案 0 :(得分:2)
尝试使用__InstanceDeletionEvent
WMI事件
string queryString = string.Format("SELECT * FROM __InstanceDeletionEvent WITHIN {0} WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Handle={1}", wmiPollingInSeconds, processID);