¿Cómo puedo programar un bat o cmd para que detenga e inicie un servicio de forma fiable con comprobación de errores (o que me avise de que no ha tenido éxito por cualquier motivo)?
net start [serviceName]
y
net stop [serviceName]
te dicen si han tenido éxito o han fracasado con bastante claridad. Por ejemplo
U:\>net stop alerter
The Alerter service is not started.
More help is available by typing NET HELPMSG 3521.
Si se ejecuta desde un archivo por lotes, tiene acceso al ERRORLEVEL del código de retorno. 0 indica éxito. Todo lo que sea más alto indica fracaso.
Como archivo bat, error.bat
:
@echo off
net stop alerter
if ERRORLEVEL 1 goto error
exit
:error
echo There was a problem
pause
La salida se ve así:
U:\>error.bat
The Alerter service is not started.
More help is available by typing NET HELPMSG 3521.
There was a problem
Press any key to continue . . .
Códigos de retorno
- 0 = Success
- 1 = Not Supported
- 2 = Access Denied
- 3 = Dependent Services Running
- 4 = Invalid Service Control
- 5 = Service Cannot Accept Control
- 6 = Service Not Active
- 7 = Service Request Timeout
- 8 = Unknown Failure
- 9 = Path Not Found
- 10 = Service Already Running
- 11 = Service Database Locked
- 12 = Service Dependency Deleted
- 13 = Service Dependency Failure
- 14 = Service Disabled
- 15 = Service Logon Failure
- 16 = Service Marked For Deletion
- 17 = Service No Thread
- 18 = Status Circular Dependency
- 19 = Status Duplicate Name
- 20 = Status Invalid Name
- 21 = Status Invalid Parameter
- 22 = Status Invalid Service Account
- 23 = Status Service Exists
- 24 = Service Already Paused
Edición 20.04.2015
Códigos de retorno: El comando NET no devuelve los códigos de retorno documentados de la clase Win32_Service (Service Not Active, Service Request Timeout, etc.) y para muchos errores simplemente devolverá Errorlevel 2.
Mire aquí: http://ss64.com/nt/net_service.html
Puede utilizar el comando NET START y luego comprobar la variable de entorno ERRORLEVEL, por ejemplo
net start [your service]
if %errorlevel% == 2 echo Could not start service.
if %errorlevel% == 0 echo Service started successfully.
echo Errorlevel: %errorlevel%
Descargo de responsabilidad: He escrito esto de la parte superior de mi cabeza, pero creo que'va a funcionar.
Utilizar los códigos de retorno de net start
y net stop
me parece el mejor método. Prueba a ver esto: Códigos de retorno de Net Start.