问题
I need to start a service from batch file (using sc start XXX
), but ONLY if it is configured with an automatic start up type.
I read the instructions of sc /?
and I tried calling first to sc qc XXX
command in order to query for it's configuration and then use findstr on the result, but I got the following error after sc qc XXX
command:
[SC] QueryServiceConfig FAILED 122:
The data area passed to a system call is too small.
[SC] GetServiceConfig needs 718 bytes
The specified service does not exist as an installed service.
Which is odd, because I am able to call sc config XXX
and stop/start it from command line.
Am I missing something? Is there a better way to do it?
回答1:
Ok, I just figured it out.
First, I must apologize , since the original error was actually:
[SC] QueryServiceConfig FAILED 122:
The data area passed to a system call is too small.
[SC] GetServiceConfig needs 718 bytes
and not
[SC] OpenService FAILED 1060:
as I first said.
Apparently, I had to explicitly add a buffer size to my service : sc qc XXX 1000
After doing that, i noticed that BINARY_PATH_NAME field was extremely long for XXX, so I guess that default memory allocation was not enough.
Now, since I basically owe StackOverflow my career, I will post my full code :)
rem start a service, but only if it is configured as automatic, and only if it isn't running already
for /F "tokens=3 delims=: " %%H in ('sc qc %xxx% 1000^| findstr "START_TYPE"') do (
if /I "%%H" EQU "AUTO_START" (
rem check if service is stopped
for /F "tokens=3 delims=: " %%H in ('sc query %xxx% ^| findstr "STATE"') do (
if /I "%%H" EQU "STOPPED" (
echo net start %xxx%
net start %xxx%
) else (
echo %xxx% is already running
)
)
) else (
echo Skipping %xxx% since it's not defined as automatic start
)
)
来源:https://stackoverflow.com/questions/19252187/how-to-check-service-startup-type-from-batch-script-in-windows-7