使用C#终止远程计算机上的进程

时间:2008-12-07 21:31:36

标签: c# .net process kill

This仅帮助杀死本地计算机上的进程。如何终止远程计算机上的进程?

3 个答案:

答案 0 :(得分:10)

您可以使用wmi。或者,如果您不介意使用外部可执行文件,请使用pskill

答案 1 :(得分:3)

我喜欢这个(类似于穆巴沙尔的回答):

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);
}

答案 2 :(得分:1)

我使用以下代码。 psKill也是一个很好的方法,但有时你需要检查一些其他的东西,例如在我的情况下远程机器运行相同进程的多个实例但具有不同的命令行参数,所以下面的代码为我工作。

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;
                }
            }
       }
}