我可以从.net项目远程启动或停止服务。
ConnectionOptions options = new ConnectionOptions();
options.Username = @"192.168.36.22\test";
options.Password = "test";
ManagementScope scope = new ManagementScope(@"\\192.168.36.22\root\cimv2", options);
scope.Connect();
ManagementOperationObserver Stop = new ManagementOperationObserver();
Stop.Completed += new CompletedEventHandler(Stop_CallBack);
try
{
string NameServices = "ArcGIS Server";
WqlObjectQuery query = new WqlObjectQuery("SELECT * FROM Win32_Service WHERE Name=\"" + NameServices + "\"");
ManagementObjectSearcher find = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject spooler in find.Get())
{
spooler.InvokeMethod("StopService", new object[] { });
spooler.InvokeMethod(Start, "StopService", new object[] { });
}
}
....
如何重新启动此服务?
答案 0 :(得分:19)
您可以像这样使用ServiceController类:
ServiceController sc = new ServiceController("ArcGIS Server", "192.168.36.22");
sc.Start();
sc.Stop();
这可以节省您编写所有代码以与WMI交互的麻烦。请注意,要使用ServiceController类,您必须添加对System.ServiceProcess程序集的引用。
答案 1 :(得分:0)
服务控制器对我不起作用,所以我使用Cmd做到了。
Process.Start("CMD.exe", "/C sc \\\\remoteMachine stop \"serviceName\"&sc \\\\remoteMachine start \"serviceName\"");
为解决凭据问题,我使用了https://stackoverflow.com/a/5433640/2179222答案中的类。
所以最后看起来像这样:
private static void RestartService(string remoteMachine, string serviceName, string userName, string password)
{
using (new NetworkConnection($"\\\\{remoteMachine}", new NetworkCredential(userName, password)))
{
Process.Start("CMD.exe", $"/C sc \\\\{remoteMachine} stop \"{serviceName}\"&sc \\\\{remoteMachine} start \"{serviceName}\"");
}
}
答案 2 :(得分:-4)
我尝试连接时遇到了类似的问题,只需在“用户”中添加您的计算机名称为admin即可。目标机器的组,您将能够获取数据。