2

This only helps kills processes on the local machine. How do I kill processes on remote machines?

Community
  • 1
  • 1
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • I don't see anything in your link stating that it won't work remotely. Did I miss something or do you have documentation stating that it will not work? – Terry Apr 10 '14 at 19:59

3 Answers3

10

You can use wmi. Or, if you don't mind using external executable, use pskill

Igal Serban
  • 10,558
  • 3
  • 35
  • 40
3

I like this (similar to answer from Mubashar):

ManagementScope managementScope = new ManagementScope("\\\\servername\\root\\cimv2");
managementScope.Connect();
ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_Process Where Name = 'processname'");
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, objectQuery);
ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
foreach (ManagementObject managementObject in managementObjectCollection)
{
    managementObject.InvokeMethod("Terminate", null);
}
lbmouse
  • 31
  • 1
1

I use the following code. psKill is also a good way to go but sometimes you need to check the some other stuff, for example in my case remote machine was running multiple instances of same process but with different command line arguments, so following code worked for me.

ConnectionOptions connectoptions = new ConnectionOptions();
connectoptions.Username = string.Format(@"carpark\{0}", "domainOrWorkspace\RemoteUsername");
connectoptions.Password = "remoteComputersPasssword";

ManagementScope scope = new ManagementScope(@"\\" + ipAddress + @"\root\cimv2");
scope.Options = connectoptions;

SelectQuery query = new SelectQuery("select * from Win32_Process where name = 'MYPROCESS.EXE'");

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
       ManagementObjectCollection collection = searcher.Get();

       if (collection.Count > 0)
       {
           foreach (ManagementObject mo in collection)
           {
                uint processId = (uint)mo["ProcessId"];
                string commandLine = (string) mo["CommandLine"];

                string expectedCommandLine = string.Format("MYPROCESS.EXE {0} {1}", deviceId, deviceType);

                if (commandLine != null && commandLine.ToUpper() == expectedCommandLine.ToUpper())
                {
                     mo.InvokeMethod("Terminate", null);
                     break;
                }
            }
       }
}
Mubashar
  • 12,300
  • 11
  • 66
  • 95