如何找到Windows服务的可执行路径

时间:2019-07-11 08:53:44

标签: c# cmd windows-services executable-path

我正在尝试查找正在运行的服务的可执行路径,并且已经查看了ServiceBase,但没有指示该路径的属性。 ServiceController offer any kind of help也没有。

ServiceBase []services=ServiceController.GetServices();
IEnumerable<string> paths=services.Select(x=> x. ? );

我也尝试使用sc qc cmd命令,但似乎不适用于特定服务

            Process proc = new Process();
            var info = new ProcessStartInfo();
            info.FileName = "cmd.exe";
            info.Arguments = "sc qc \"[service-name]\" | find \"BINARY_PATH_NAME\"";
            proc.StartInfo = info;
            proc.Start();
            var data = await proc.StandardOutput.ReadToEndAsync();

它引发错误:

  

System.InvalidOperationException:'StandardOut尚未重定向   或该过程尚未开始。”

是否有任何方法可以获取特定服务或所有服务的可执行文件的路径?

1 个答案:

答案 0 :(得分:1)

您可以使用 WMI

例如(使用WMI Code Creator):

            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Service");
                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("DisplayName: {0}", queryObj["DisplayName"]);
                    Console.WriteLine("Name: {0}", queryObj["Name"]);
                    Console.WriteLine("PathName: {0}", queryObj["PathName"]);
                    Console.WriteLine("ProcessId: {0}", queryObj["ProcessId"]);
                    Console.WriteLine("-----------------------------------");
                }
            }
            catch (ManagementException me)
            {
                MessageBox.Show("An error occurred while querying for WMI data: " + me.Message);
            }