我试图杀死远程计算机上的进程。但我得到错误。我做错了什么,如何才能做到这一点?
我的代码:
var iu = new ImpersonateUser();
try
{
iu.Impersonate(Domain, _userName, _pass);
foreach (var process in Process.GetProcessesByName("notepad", "RemoteMachine"))
{
string processPath = pathToExe; //Is set as constant (and is correct)
process.Kill();
Thread.Sleep(3000);
Process.Start(processPath);
}
}
catch (Exception ex)
{
lblStatus.Text = ex.ToString();
}
finally
{
iu.Undo();
}
为了澄清ImpersonateUser,它让我以正确的用户权限登录到远程计算机。所以问题不存在。当我调试并检查过程对象时,在这种情况下我找到了记事本的正确进程ID。所以连接工作正常。但是当我试图杀死这个过程时,我得到了这个错误:
System.NotSupportedException: Feature is not supported for remote machines. at System.Diagnostics.Process.EnsureState
答案 0 :(得分:20)
System.Diagnostics.Process
类无法终止远程进程。您可以使用System.Management
命名空间(确保设置引用),以使用WMI。
下面是一个简单的例子。
var processName = "iexplore.exe";
var connectoptions = new ConnectionOptions();
connectoptions.Username = @"YourDomainName\UserName";
connectoptions.Password = "User Password";
string ipAddress = "192.168.206.53";
ManagementScope scope = new ManagementScope(@"\\" + ipAddress + @"\root\cimv2", connectoptions);
// WMI query
var query = new SelectQuery("select * from Win32_process where name = '" + processName + "'");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
foreach (ManagementObject process in searcher.Get()) // this is the fixed line
{
process.InvokeMethod("Terminate", null);
}
}
Console.ReadLine();