gpt4 book ai didi

c# - 如何使用 WMI 确保进程在远程机器上结束?

转载 作者:太空宇宙 更新时间:2023-11-03 11:18:27 25 4
gpt4 key购买 nike

此方法使用 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();
}

最佳答案

尝试使用 __InstanceDeletionEvent WMI 事件代替

string queryString = string.Format("SELECT * FROM __InstanceDeletionEvent WITHIN {0} WHERE TargetInstance ISA 'Win32_Process' AND TargetInstance.Handle={1}", wmiPollingInSeconds, processID);

关于c# - 如何使用 WMI 确保进程在远程机器上结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11877740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com