【问题标题】:Running command from command prompt and get output从命令提示符运行命令并获取输出
【发布时间】:2018-04-17 14:05:35
【问题描述】:

我正在尝试编写一个从命令提示符运行命令并显示命令输出的代码。基本上,该命令将检查窗口服务的状态,如果它正在运行或停止。代码如下:

Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();

startInfo.FileName = @"cmd.exe";
startInfo.Arguments = "sc query \"My Service\" | findstr STATE";
process.StartInfo = startInfo;
process.StartInfo.RedirectStandardOutput = true;
process.Start();

while (!process.StandardOutput.EndOfStream)
{
    string line = process.StandardOutput.ReadLine();
}

如果我在命令行上运行命令:

sc query "My Service" | findstr STATE

这会返回我:

STATE              : 1  STOPPED

但是如果我在上面运行我的 c# 代码,什么都不会发生,并且在一段时间后我的浏览器会抛出错误:

HTTP 错误 502.3 - 网关错误 指定的 CGI 应用程序遇到错误,服务器终止了进程。

不确定这里还缺少什么。

【问题讨论】:

  • 你为什么执行cmd.exe而不是sc
  • 您是否尝试在 Web 应用程序中执行此操作?您可能遇到授权问题。通常,对于 500 状态,应用程序事件日志中会出现错误报告(包括更多详细信息)。
  • @mjwills 看到下面的回复为什么我不使用 SC
  • 请记住,您会在此处获得本地化响应。 STATE 的拼写可能不同
  • @Richard 是的,它是一个 mvc 网络应用程序。

标签: c# command command-prompt


【解决方案1】:

既然可以用简单的代码完成,为什么还要使用 cmd 呢?

 ServiceController[] services = ServiceController.GetServices();
 foreach(ServiceController service in services)
 {
  If (service.ServiceName == "name here")
  { 
Console.WriteLine(service.ServiceName+"=="+ service.Status);
 }}

或者更好的版本:

  try
{
using( ServiceController sc = new ServiceController(name here) )
{
    return sc.Status == ServiceControllerStatus.Running;
}
}
catch( ArgumentException ) { return false; }
catch( Win32Exception ) { return false; }

另一种方式(OP 最后提到他在网络应用程序中这样做:)):

  using System.ServiceProcess;

  ServiceController sc = new ServiceController(SERVICENAME);

  switch (sc.Status)
  {
    case ServiceControllerStatus.Running:
    return "Running";
  }

【讨论】:

  • 我一直在努力让“服务控制器”工作。我首先尝试使用服务控制器类。但它不断抛出错误:“无法在计算机上打开服务控制管理器''。此操作可能需要其他权限。”在我们的网络服务器上。我已将正在运行的帐户添加到管理员组并已授予远程访问权限,但没有任何效果。所以我想研究检查服务状态的其他可能性。
  • 还有一件事,请确保在web app 中包含您正在执行此操作的信息:(
  • 现在看看我的回答 :)
  • 问题是一旦它尝试访问服务控制器就会抛出拒绝访问错误。所以我是否通过服务名称并不重要。我将更新我的问题,包括网络应用程序
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-30
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 2018-05-01
相关资源
最近更新 更多