【问题标题】:Windows command to get service status?Windows命令获取服务状态?
【发布时间】:2010-10-22 13:47:05
【问题描述】:

我需要在我的批处理脚本结束时知道服务的状态,该脚本使用“net stop thingie”和“net start thingie”重新启动服务。

在我最喜欢的理想世界中,我想将状态通过电子邮件发送给自己,在寒冷的冬夜阅读,用我知道运行正常的服务器的温暖和舒适来安慰自己。

请注意,我使用的是 Windows server 2003 平台,批处理文件似乎是最佳选择。我不介意使用其他东西,并且非常愿意接受建议,但只是为了知识(作为僵尸渴望大脑,我想,为什么不给我自己的大脑充气),是否有一个命令可以让我检查关于服务的状态,在命令行中?

我应该将命令的输出重定向到文件吗?

我的裤子去哪儿了? (天哪,我真的希望插入的幽默不会侮辱任何人。现在是星期三早上,我也需要幽默:P)

[编辑:]我使用的解决方案(不再)可从--link redacted--下载--

它作为一个任务集在晚上执行,早上检查我的电子邮件,看看服务是否已经正确重启。

【问题讨论】:

    标签: windows-services batch-file windows-server-2003


    【解决方案1】:

    我的目的是创建一个脚本来打开和关闭服务(在 1 个脚本中)

    net start NameOfSercive 2>nul
    if errorlevel 2 goto AlreadyRunning
    if errorlevel 1 goto Error
    

    ...

    帮了大忙!! TYVM z666

    但是当例如服务被禁用(也错误级别=2?)它进入“AlreadyRuning”并且永远不会出现

    if errorlevel 1 goto Error  ?!!
    

    我想要那个案例的输出......

     :AlreadyRunning
     net stop NameOfSercive
     if errorlevel 1 goto Error
    
    
     :Error
     Echo ERROR!!1!
     Pause
    

    我的 2 美分,希望对您有所帮助

    【讨论】:

      【解决方案2】:

      Ros 我发布的代码也是为了了解有多少服务正在运行...

      想象一下,您想知道有多少服务类似于 Oracle*,然后您将 Oracle 替换为 NameOfSercive...,您将获得在变量 %CountLines% 上运行的 Oracle* 等服务的数量,如果您想做某事,如果只有 4 个你可以做这样的事情:

      IF 4==%CountLines% GOTO FourServicesAreRunning

      这更强大...并且您的代码不会让您知道所需的服务是否正在运行...如果有另一个以相同名称开头的 srecive...想象一下: -ServiceOne -ServiceOnePersonal

      如果您搜索 ServiceOne,但它只在运行 ServiceOnePersonal,您的代码会告诉 ServiceOne 正在运行...

      我的代码可以轻松更改,因为它读取文件的所有行并逐行读取它还可以对每个服务执行任何您想要的操作...请参阅:

      @ECHO OFF
      REM Put here any code to be run before check for Services
      
      SET TemporalFile=TemporalFile.TXT
      NET START > %TemporalFile%
      SET CountLines=0
      FOR /F "delims=" %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
      SETLOCAL EnableDelayedExpansion
      SET CountLine=0
      FOR /F "delims=" %%X IN (%TemporalFile%) DO @(
       SET /A CountLine=1+CountLine
      
       REM Do whatever you want to each line here, remember first and last are special not service names
      
       IF 1==!CountLine! (
      
         REM Do whatever you want with special first line, not a service.
      
       ) ELSE IF %CountLines%==!CountLine! (
      
         REM Do whatever you want with special last line, not a service.
      
       ) ELSE (
      
         REM Do whatever you want with rest lines, for each service.
         REM    For example echo its position number and name:
      
         echo !CountLine! - %%X
      
         REM    Or filter by exact name (do not forget to not remove the three spaces at begining):
         IF "   NameOfService"=="%%X" (
      
           REM Do whatever you want with Service filtered.
      
         )
       )
      
       REM Do whatever more you want to all lines here, remember two first are special as last one
      
      )
      
      DEL -P %TemporalFile% 2>nul
      SET TemporalFile=
      
      REM Put here any code to be run after check for Services
      

      当然它只列出正在运行的服务,我不知道 net 可以通过什么方式列出未运行的服务...

      希望对你有帮助!!!

      【讨论】:

        【解决方案3】:

        我看到“Nick Kavadias”这样说:

        “根据这个http://www.computerhope.com/nethlp.htm应该是NET START /LIST ...”

        如果您在 Windows XP 中键入:

        NET START /LIST
        

        你会得到一个错误,只需输入代替

        NET START
        

        /LIST 仅适用于 Windows 2000...如果您完全阅读此类网页,您会发现 /LIST 仅适用于 Windows 2000 部分。

        希望对你有帮助!!!

        【讨论】:

          【解决方案4】:

          也许这可能是启动服务并检查结果的最佳方式

          当然,在 File.BAT 之类的 Batch 中放置类似此示例的内容,但只需将“NameOfSercive”替换为您想要的服务名称,然后将 REM 行替换为您自己的代码:

          @ECHO OFF
          
          REM Put whatever your Batch may do before trying to start the service
          
          net start NameOfSercive 2>nul
          if errorlevel 2 goto AlreadyRunning
          if errorlevel 1 goto Error
          
          REM Put Whatever you want in case Service was not running and start correctly
          
          GOTO ContinueWithBatch
          
          :AlreadyRunning
          REM Put Whatever you want in case Service was already running
          GOTO ContinueWithBatch
          
          :Error
          REM Put Whatever you want in case Service fail to start
          GOTO ContinueWithBatch
          
          :ContinueWithBatch
          
          REM Put whatever else your Batch may do
          

          另一件事是在不更改状态的情况下检查其状态,因为有一种更简单的方法可以做到这一点,只需运行:

          net start
          

          因此,如果没有参数,它将显示一个包含所有已启动服务的列表...

          所以一个简单的 grep 或在管道上查找就可以了...

          当然,在 File.BAT 之类的 Batch 中放置类似此示例的内容,但只需将“NameOfSercive”替换为您想要的服务名称,然后将 REM 行替换为您自己的代码:

          @ECHO OFF
          
          REM Put here any code to be run before check for Service
          
          SET TemporalFile=TemporalFile.TXT
          NET START | FIND /N "NameOfSercive" > %TemporalFile%
          SET CountLines=0
          FOR /F %%X IN (%TemporalFile%) DO SET /A CountLines=1+CountLines
          IF 0==%CountLines% GOTO ServiceIsNotRunning
          
          REM Put here any code to be run if Service Is Running
          
          GOTO ContinueWithBatch
          
          :ServiceIsNotRunning
          
          REM Put here any code to be run if Service Is Not Running
          
          GOTO ContinueWithBatch
          :ContinueWithBatch
          DEL -P %TemporalFile% 2>nul
          SET TemporalFile=
          
          REM Put here any code to be run after check for Service
          

          希望这能有所帮助!!这是我通常使用的。

          【讨论】:

          • 所有这些带有临时文件的东西都可以用(NET START | FIND "NameOfService" > nul) && SET ServiceRunning=1GOTO替换,而不是设置标志。
          【解决方案5】:

          再看看:

          网络开始 |查找“服务名称”> nul IF errorlevel 1 ECHO 服务没有运行

          刚刚复制自: http://ss64.com/nt/sc.html

          【讨论】:

          • + for "NET START",不是获取正在运行的服务列表的明显方式
          【解决方案6】:

          如果您可以使用 PowerShell...

          Get-Service -DisplayName *Network* | ForEach-Object{Write-Host $_.Status : $_.Name}
          

          会给你...

          Stopped : napagent
          Stopped : NetDDE
          Stopped : NetDDEdsdm
          Running : Netman
          Running : Nla
          Stopped : WMPNetworkSvc
          Stopped : xmlprov
          

          如果您只需要检查一项服务,您可以将 ****Network**** 替换为特定的服务名称。

          【讨论】:

            【解决方案7】:

            我不确定您是否可以通过电子邮件发送批处理文件中的结果。如果我可以提出可以解决您的问题 vbscript 的替代建议。我对 vbscript 还不够好,但您可以使用它来查询在本地机器上运行的服务。下面的脚本将通过电子邮件向您发送运行该脚本的机器上运行的所有服务的状态。您显然想要替换 smtp 服务器和电子邮件地址。如果您是域的一部分并且以特权用户身份运行此脚本(他们必须是远程计算机上的管理员),您也可以通过将 localhost 替换为 fqdn 来查询远程计算机。

            Dim objComputer, objMessage
            Dim strEmail
            
            ' If there is an error getting the status of a service it will attempt to move on to the next one
            On Error Resume Next
            
            ' Email Setup
            Set objMessage = CreateObject("CDO.Message")
            objMessage.Subject = "Service Status Report"
            objMessage.From = "service_report@noreply.net"
            objMessage.To = "youraddress@example.net"
            objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
            
            'Name or IP of Remote SMTP Server
            objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.example.net"
            
            'Server port (typically 25)
            objMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
            
            Set objComputer = GetObject("WinNT://localhost")
            objComputer.Filter = Array("Service")
            
            For Each aService In objComputer
            strEmail = strEmail &chr(10) & aService.Name & "=" & aService.Status
            Next
            
            objMessage.TextBody = strEmail
            objMessage.Configuration.Fields.Update
            objMessage.Send
            

            希望对您有所帮助!享受吧!

            编辑:还有一件事,服务状态为 4 表示服务正在运行,服务状态为 1 表示未运行。我不确定 2 或 3 是什么意思,但我敢打赌他们正在停止/开始。

            【讨论】:

            • 非常感谢这个脚本!将使用它附加在我的批处理文件中,以简单而有效的形式调用 vb 脚本的 shell,这很容易由服务器处理:P
            • 结合我选择的其他脚本作为一个好的答案,我的停止/重新启动/邮件结果周期即将完成。
            【解决方案8】:

            您可以在您的服务上致电net start "service name"。如果它没有启动,它会启动它并返回errorlevel=0,如果它已经启动它会返回errorlevel=2。

            【讨论】:

            • 不知道为什么我对此投了反对票,但由于他使用 bat 文件通过 net start 命令启动服务,并且它内置在命令中以返回错误代码,最简单的方法是只需检查错误代码。但是如果强制为它创建一个单独的vbs而不是检查返回,我不在乎。
            【解决方案9】:

            你试过sc.exe吗?

            C:\> for /f "tokens=2*" %a in ('sc query audiosrv ^| findstr STATE') do echo %b
            4  RUNNING
            
            C:\> for /f "tokens=2*" %a in ('sc query sharedaccess ^| findstr STATE') do echo %b
            1  STOPPED
            

            请注意,在批处理文件中,您需要将每个百分号加倍。

            【讨论】:

            • 或更简单(但类似):for /f "tokens=4" %a in ('sc query YOURSERVICENAME ^| findstr STATE') do echo %a
            【解决方案10】:

            根据这个http://www.computerhope.com/nethlp.htm 它应该是 NET START /LIST 但我无法通过 XP 框让它工作。我确信有一些 WMI 会给你这个列表。

            【讨论】:

              【解决方案11】:

              使用 Windows 脚本:

              Set ComputerObj = GetObject("WinNT://MYCOMPUTER")    
              ComputerObj.Filter = Array("Service")    
              For Each Service in ComputerObj    
                  WScript.Echo "Service display name = " & Service.DisplayName    
                  WScript.Echo "Service account name = " & Service.ServiceAccountName    
                  WScript.Echo "Service executable   = " & Service.Path    
                  WScript.Echo "Current status       = " & Service.Status    
              Next
              

              您可以轻松过滤以上内容以获得您想要的特定服务。

              【讨论】:

              • 已选中,因为不需要安装。谢谢你们!
              【解决方案12】:

              使用pstools - 特别是psservice 和“查询” - 例如:

              psservice query "serviceName"
              

              【讨论】:

              • 这是我最喜欢的^^
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-09-05
              • 1970-01-01
              • 1970-01-01
              • 2020-01-16
              • 2016-03-18
              • 2021-04-13
              • 1970-01-01
              相关资源
              最近更新 更多