简体   繁体   English

如何使用wmi杀死远程计算机上的进程

[英]How to kill process on remote computer with wmi

I'm trying to kill a process on a remote computer, but it's not working, and i'm not getting any errors.我正在尝试终止远程计算机上的进程,但它不起作用,而且我没有收到任何错误。 I'm using this code:我正在使用此代码:

            ManagementScope scope = new ManagementScope("\\\\" + txtMaquina.Text + "\\root\\cimv2");
            scope.Connect();
            ObjectQuery query = new ObjectQuery("select * from Win32_process where name = '" + lstProcessos.SelectedItem.ToString() + "'");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection objectCollection = searcher.Get();
            foreach (ManagementObject managementObject in objectCollection)
                managementObject.InvokeMethod("Terminate", null);

The computer name is txtMaquina.Text and the process name i'm getting from a selected item on a ListView计算机名称是txtMaquina.Text和我从ListView上的选定项目中获取的进程名称

Someone have any idea what's wrong here?有人知道这里有什么问题吗?

and i'm not having any error我没有任何错误

That's because you don't actually check for an error.那是因为您实际上并没有检查错误。 You are probably hoping for an exception but that's not what the Terminate method does.您可能希望出现异常,但这不是 Terminate 方法所做的。 It returns an error code.它返回一个错误代码。 You cannot ignore the return value of ManagementObject.InvokeMethod().您不能忽略 ManagementObject.InvokeMethod() 的返回值。

So start solving the problem by getting that exception you don't have right now:因此,通过获取您现在没有的异常开始解决问题:

foreach (ManagementObject managementObject in objectCollection) {
    int reason = (int)managementObject.InvokeMethod("Terminate", null);
    switch (reason) {
        case 0: break;
        case 2: throw new Exception("Access denied"); break;
        case 3: throw new Exception("Insufficient privilege"); break;
        case 8: throw new Exception("Unknown failure"); break;
        case 9: throw new Exception("Path not found"); break;
        case 21: throw new Exception("Invalid parameter"); break;
        default: throw new Exception("Terminate failed with error code " + reason.ToString()); break;
    }
}

Now you know where to start looking.现在你知道从哪里开始寻找。

Your problem comes from the parameters :您的问题来自参数:

  • txtMaquina.Text: must be the machine name. txtMaquina.Text:必须是机器名称。
  • lstProcessos.SelectedItem.ToString(): must be the exe name like Taskmgr.exe lstProcessos.SelectedItem.ToString():必须是像Taskmgr.exe这样的exe名称

I've run your code on my computer and I works fine with the right values in the input parameters.我已经在我的计算机上运行了您的代码,并且在输入参数中使用正确的值时我可以正常工作。 As Brett said, you could debug it, use immediate windows or run the code snippet in an unit test fixture.正如 Brett 所说,您可以调试它、使用即时窗口或在单元测试装置中运行代码片段。

我在代码项目中使用此解决方案解决了我的问题: http : //www.codeproject.com/Articles/18146/How-To-Almost-Everything-In-WMI-via-C-Part-Proce

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM