Kill a process on a remote machine in C#

2019-05-23 09:34发布

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

3条回答
2楼-- · 2019-05-23 09:46

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);
}
查看更多
The star\"
3楼-- · 2019-05-23 09:53

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

查看更多
聊天终结者
4楼-- · 2019-05-23 09:57

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;
                }
            }
       }
}
查看更多
登录 后发表回答