2008-12-07 11 views
2

This aide seulement à tuer les processus sur la machine locale. Comment puis-je tuer des processus sur des machines distantes?Tuer un processus sur une machine distante en C#

+0

Je ne vois rien dans votre lien indiquant que cela ne fonctionnera pas à distance. Est-ce que j'ai manqué quelque chose ou avez-vous des documents indiquant que cela ne fonctionnera pas? – Terry

Répondre

10

Vous pouvez utiliser wmi. Ou, si cela ne vous dérange pas d'utiliser un exécutable externe, utilisez pskill

+0

un exemple de code? – Kiquenet

+0

Je ne connaissais pas pskill, ça m'a juste sauvé la journée! –

1

J'utilise le code suivant. psKill est aussi un bon moyen d'y aller mais parfois vous devez vérifier les autres choses, par exemple dans mon cas la machine distante exécutait plusieurs instances du même processus mais avec des arguments de ligne de commande différents, donc le code suivant a fonctionné pour moi.

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

J'aime (similaire à répondre de 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); 
} 
Questions connexes