我希望查询远程机器上以特定用户身份运行的服务列表,并检查每个服务的状态。我正在构建自定义控制台。
ServiceController.GetServices("machineName")
返回一个包含指定机器的ServiceController
对象数组。
这段代码:
namespace AtYourService
{
using System;
using System.ServiceProcess;
class Program
{
static void Main(string[] args)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
Console.WriteLine(
"The {0} service is currently {1}.",
service.DisplayName,
service.Status);
}
Console.Read();
}
}
}
产生:
The Application Experience service is currently Running.
The Andrea ST Filters Service service is currently Running.
The Application Layer Gateway Service service is currently Stopped.
The Application Information service is currently Running.
etc...
当然,我使用无参版本在我的计算机上获取服务。
using System.Management;
static void EnumServices(string host, string username, string password)
{
string ns = @"root\cimv2";
string query = "select * from Win32_Service";
ConnectionOptions options = new ConnectionOptions();
if (!string.IsNullOrEmpty(username))
{
options.Username = username;
options.Password = password;
}
ManagementScope scope =
new ManagementScope(string.Format(@"\\{0}\{1}", host, ns), options);
scope.Connect();
ManagementObjectSearcher searcher =
new ManagementObjectSearcher(scope, new ObjectQuery(query));
ManagementObjectCollection retObjectCollection = searcher.Get();
foreach (ManagementObject mo in retObjectCollection)
{
Console.WriteLine(mo.GetText(TextFormat.Mof));
}
}
ServiceController.GetServices()
。namespace ServiceName
{
using System;
using System.ServiceProcess;
class Service
{
public static bool IsServiceInstalled(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController service in services)
{
if (service.ServiceName == serviceName)
return true;
}
return false;
}
}
}