Windows command to get service status?

后端 未结 12 786
渐次进展
渐次进展 2021-02-01 04:48

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 id

12条回答
  •  广开言路
    2021-02-01 05:11

    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.

提交回复
热议问题