[windows-services] Windows command to get service status?

I need to know the status of a service at the end of my batch script which restarts services using "net stop thingie" and "net start thingie".

In my most favorite ideal world, I would like to e-mail the state to myself, to read on cold winter nights, to reassure myself with the warmth and comfort of a server that I know is running right.

Just for you to know, I'm using a Windows server 2003 platform, and a batch file seemed the best choice. I don't mind using something else, and would be very open to suggestions, but just for the sake of knowledge (as a zombie craves brains, I thought, why not inflate my own), is there a command that allows me to check on the status of a service, in command line?

Should I just redirect the output of the command to a file?

Where the hell are my pants? (Gosh, I really do hope the humor inserted in this will not insult anyone. It's Wednesday morning, and humor I do need too :P)

[Edit:] The solution I used is (no longer) available for download from --link redacted--

It is used as a task set to be executed during the night, and checking my e-mail in the morning, I see whether or not the service has correctly restarted.

This question is related to windows-services batch-file windows-server-2003

The answer is


You can call net start "service name" on your service. If it's not started, it'll start it and return errorlevel=0, if it's already started it'll return errorlevel=2.


Ros the code i post also is for knowing how many services are running...

Imagine you want to know how many services are like Oracle* then you put Oracle instead of NameOfSercive... and you get the number of services like Oracle* running on the variable %CountLines% and if you want to do something if there are only 4 you can do something like this:

IF 4==%CountLines% GOTO FourServicesAreRunning

That is much more powerfull... and your code does not let you to know if desired service is running ... if there is another srecive starting with same name... imagine: -ServiceOne -ServiceOnePersonal

If you search for ServiceOne, but it is only running ServiceOnePersonal your code will tell ServiceOne is running...

My code can be easly changed, since it reads all lines of the file and read line by line it can also do whatever you want to each service... see this:

@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

Of course it only list running services, i do not know any way net can list not running services...

Hope this helps!!!


according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST but i can't get it to work on by XP box. I'm sure there's some WMI that will give you the list.


Maybe this could be the best way to start a service and check the result

Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:

@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

Another thing is to check for its state without changing it, for that there is a much more simple way to do it, just run:

net start

As that, without parameters it will show a list with all services that are started...

So a simple grep or find after it on a pipe would fit...

Of course from inside a Batch like File.BAT put something like this example but just replace "NameOfSercive" with the service name you want and replace the REM lines with your own code:

@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

Hope this can help!! It is what i normally use.


my intention was to create a script which switches services ON and OFF (in 1 script)

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

...

Helped a lot!! TYVM z666

but when e.g. service is disabled(also errorlevel =2?)it goes to "AlreadyRuning"and never comes to

if errorlevel 1 goto Error  ?!!

i wanted an output for that case ...

 :AlreadyRunning
 net stop NameOfSercive
 if errorlevel 1 goto Error


 :Error
 Echo ERROR!!1!
 Pause

my 2 Cents, hope this helps


Well I'm not sure about whether you can email the results of that from a batch file. If I may make an alternate suggestion that would solve your problem vbscript. I am far from great with vbscript but you can use it to query the services running on the local machine. The script below will email you the status of all of the services running on the machine the script gets run on. You'll obviously want to replace the smtp server and the email address. If you're part of a domain and you run this script as a privileged user (they have to be an administrator on the remote machine) you can query remote machines as well by replacing localhost with the 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 = "[email protected]"
objMessage.To = "[email protected]"
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

Hope this helps you! Enjoy!

Edit: Ahh one more thing a service status of 4 means the service is running, a service status of 1 means it's not. I'm not sure what 2 or 3 means but I'm willing to bet they are stopping/starting.


Have you tried 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

Note that inside a batch file you'd double each percent sign.


look also hier:

NET START | FIND "Service name" > nul IF errorlevel 1 ECHO The service is not running

just copied from: http://ss64.com/nt/sc.html


Well i see "Nick Kavadias" telling this:

"according to this http://www.computerhope.com/nethlp.htm it should be NET START /LIST ..."

If you type in Windows XP this:

NET START /LIST

you will get an error, just type instead

NET START

The /LIST is only for Windows 2000... If you fully read such web you would see the /LIST is only on Windows 2000 section.

Hope this helps!!!


If PowerShell is available to you...

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

Will give you...

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

You can replace the ****Network**** with a specific service name if you just need to check one service.


Using pstools - in particular psservice and "query" - for example:

psservice query "serviceName"

Examples related to windows-services

Can't start Tomcat as Windows Service Error 1053 the service did not respond to the start or control request in a timely fashion How to solve "The specified service has been marked for deletion" error Service will not start: error 1067: the process terminated unexpectedly How to get all Windows service names starting with a common word? Windows service with timer Windows service on Local Computer started and then stopped error Windows service start failure: Cannot start service from the command line or debugger "Automatic" vs "Automatic (Delayed start)" How to install node.js as windows service?

Examples related to batch-file

'ls' is not recognized as an internal or external command, operable program or batch file '' is not recognized as an internal or external command, operable program or batch file XCOPY: Overwrite all without prompt in BATCH CanĀ“t run .bat file under windows 10 Execute a batch file on a remote PC using a batch file on local PC Windows batch - concatenate multiple text files into one How do I create a shortcut via command-line in Windows? Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat Curl not recognized as an internal or external command, operable program or batch file Best way to script remote SSH commands in Batch (Windows)

Examples related to windows-server-2003

Multiple -and -or in PowerShell Where-Object statement Batch file to restart a service. Windows Error message: (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) Domain Account keeping locking out with correct password every few minutes What possibilities can cause "Service Unavailable 503" error? ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach) how to get list of port which are in use on the server How do I 'svn add' all unversioned files to SVN? Windows command to get service status? How do I measure execution time of a command on the Windows command line?