Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill process on remote computer with wmi

Tags:

c#

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?

like image 206
Mathi901 Avatar asked Sep 17 '15 19:09

Mathi901


Video Answer


1 Answers

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.

like image 112
Hans Passant Avatar answered Oct 31 '22 11:10

Hans Passant