我可以使用PowerShell相当容易地做到这一点,但我正在寻找一种C#方式来做到这一点。使用PS,我可以使用Get-Service迭代集合并检查名为DependentServices和RequiredServices的集合,以获取给定服务的依赖和所需服务的列表。
我使用查询“Select * from Win32_Service”查看了WMI模型,但这会返回Win32_Service个对象的集合,这些对象似乎没有我感兴趣的集合。我觉得我我在这里错过了什么。我环顾四周并尝试了各种搜索,但我没有提出一种以C#为中心的方法。
我想查询给定的服务并获取上面提到的集合(DependentServices和RequiredServices)。对不起,如果我错过了明显的,但我真的找不到相关的主题。
答案 0 :(得分:2)
您可以使用ServiceController类:
StringBuilder sb = new System.Text.StringBuilder();
foreach (var svc in System.ServiceProcess.ServiceController.GetServices())
{
sb.AppendLine("============================");
sb.AppendLine(svc.DisplayName);
foreach (var dep in svc.DependentServices)
{
sb.AppendFormat("\t{0}", dep.DisplayName);
sb.AppendLine();
}
}
MessageBox.Show(sb.ToString());
答案 1 :(得分:2)
您可以使用Win32_DependentService
WMI类和Associators of
句子来检索相关服务。
试试这个样本
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
class Program
{
static void Main(string[] args)
{
try
{
string ComputerName = "localhost";
ManagementScope Scope;
Scope = new ManagementScope(String.Format("\\\\{0}\\root\\CIMV2", ComputerName), null);
Scope.Connect();
ObjectQuery Query = new ObjectQuery("Associators of {Win32_Service.Name='NetMan'} Where AssocClass=Win32_DependentService ResultClass=Win32_Service");
ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query);
foreach (ManagementObject WmiObject in Searcher.Get())
{
Console.WriteLine("{0,-35} {1,-40}","Name",WmiObject["Name"]);// String
}
}
catch (Exception e)
{
Console.WriteLine(String.Format("Exception {0} Trace {1}",e.Message,e.StackTrace));
}
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
}
答案 2 :(得分:1)
ServiceController sc = new ServiceController("Event Log");
ServiceController[] scServices = sc.DependentServices;
// Display the list of services dependent on the Event Log service.
if (scServices.Length == 0)
{
Console.WriteLine("There are no services dependent on {0}",
sc.ServiceName);
}
else
{
Console.WriteLine("Services dependent on {0}:",
sc.ServiceName);
foreach (ServiceController scTemp in scServices)
{
Console.WriteLine(" {0}", scTemp.DisplayName);
}
}