我正在尝试收集有关我的域中的各种服务器上运行的服务的数据。对于每个要检查的服务器,我都会获取服务列表
ServiceController[] services = ServiceController.GetServices(server);
从那里,我检查服务中的每个 ServiceController 对象的 ServiceStartMode 和 ServiceControllerStatus
if (sc.StartType == ServiceStartMode.Automatic && sc.Status != ServiceControllerStatus.Running)
我遇到的问题是自动(延迟启动)服务 - 我想从上面的条件语句中排除这些服务,但延迟启动似乎不是 ServiceStartMode 枚举的成员。
有哪些方法可以查明某项服务是否延迟启动,以便将这些服务从我的搜索中排除?
最佳答案
Windows 将其服务数据保存在注册表中的\\HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services 下。
您可以查询服务的Start 和DelayedAutostart 值来检查这一点。如果您手动将服务设置为自动(延迟启动),则仅在重新启动后才会创建 DelayedAutostart 值。
private static bool GetDelayedStatus(string serviceName, string machineName)
{
using (var regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName))
{
using (RegistryKey serviceKey = regKey.OpenSubKey(@"System\CurrentControlSet\Services\" + serviceName, false))
{
int startMode = (int)serviceKey.GetValue("Start", 0, RegistryValueOptions.None);
int delayedAutostart = (int)serviceKey.GetValue("DelayedAutostart", 0, RegistryValueOptions.None);
return startMode == 2 && delayedAutostart == 1;
}
}
}
关于C# 检查服务是否设置为自动(延迟启动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48210517/