简体   繁体   中英

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

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. It returns an error code. You cannot ignore the return value of 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.
  • lstProcessos.SelectedItem.ToString(): must be the exe name like Taskmgr.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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