I have the following Batch script which attempts to stop a couple of services (in order), wait and make sure that both have stopped, then start first service. The first service has a dependency of the second service. This is the reason for the order in stopping them, as well as the reason only one of them is started.
The services might take a while to stop after the stop command has been issued, so I need to wait and make sure that they have stopped before attempting to start them again. This is what I have come up with:
set FirstServiceName="SrvcOne"
set SecondServiceName="SrvcTwo"
set findStop=find /i "STOPPED"
set GetFirstServiceState=sc query %FirstServiceName%
set GetSecondServiceState=sc query %SecondServiceName%
:sub_StopServices
set "FirstServiceState=^"^""
for /f "delims=" %a in ('%GetFirstServiceState%^|%findStop%') do @set FirstServiceState=%a
if "%FirstServiceState%"=="" (net stop %FirstServiceName%)
set "SecondServiceState=^"^""
for /f "delims=" %a in ('%GetSecondServiceState%^|%findStop%') do @set SecondServiceState=%a
if "%SecondServiceState%"=="" (net stop %SecondServiceName%)
if "%FirstServiceState%" neq "" (if "%SecondServiceState%" neq "" (GOTO sub_StartServices) else (GOTO sub_StopServices)) else (GOTO sub_StopServices)
:sub_StartServices
net start %FirstServiceName%
exit
The problem I encountered with the code above is that the script stops on the first for line
for /f "delims=" %a in ('%GetFirstServiceState%^|%findStop%') do @set FirstServiceState=%a
with the exception
GetFirstServiceStatefindStopa was unexpected at this time
Of course, it's unexpected for me as well for when I run that line manually - it succeeds! And, assuming the service has stopped, I get the STATE line from the sc query's response.
Why does this work when run manually but not when run through the batch script?
Just a side note, in the line set "FirstServiceState=^"^"", I'm basically clearing the value of that variable. When I run the line above (the one that doesn't work) manually and the service STATE isn't STOPPED, that variables value is unaffected... I'd expect it to be nullified or have an empty string but this is not the case. It simply stays the same value. So before the test, I set the value to double-quotes.
forreplaceable parameters need escaped percent signs, so,%abecomes%%a. Have you tried this way?