Reputation: 33
I have following problem:
I want to create a batch file looping through an amount of ip addresses to stop a certain service on remote pc's.
Cause the stopping process takes some time I need to have a second loop to query the state of the service and waiting until the service reached the state STOPPED.
Set /p StartIP="Start IP (101): "
Set /p EndIP="End IP (199): "
for /L %%n IN (%StartIP%, 1, %EndeIP%) DO (
psservice -u username -p password \\192.168.8.&&n stop 'ServiceName'
:CHECK
echo 5 sek.
ping 127.0.0.1 -n 5 > nul
for /F "tokens=3 delims=: " %%H in ('psservice -u username -p password \\192.168.8.%%n query 'ServiceName' ^| findstr " STATE"') do (
if NOT %%H==STOPPED (
echo.
echo state: %%H
goto CHECK
)
echo.
echo state: %%H
)
psservice -u username -p password \\192.168.8.%%n start 'ServiceName'
)
Now the point I stuck to:
My range of numbers '%%n' from the /L loop is getting destroyed after passing the /F loop the first time.
With an example it looks like this:
Set /p StartIP="Start IP (101): 101"
Set /p EndIP="End IP (199): 105"
for /L %%n IN (101, 1, 105) DO (
psservice -u username -p password \\192.168.8.101 stop 'ServiceName'
:CHECK
echo 5 sek.
ping 127.0.0.1 -n 5 > nul
for /F "tokens=3 delims=: " %%H in ('psservice -u username -p password \\192.168.8.101 query 'ServiceName' ^| findstr " STATE"') do (
if NOT %%H==STOPPED (
echo.
echo state: %%H
goto CHECK
)
echo.
echo state: %%H
)
psservice -u username -p password \\192.168.8.%%n start 'ServiceName'
)
In this example I have the ip range 192.168.8.101 to 192.168.8.105. The batch is running well until the /F loop is run trough the first time. After this moment the %%n parameter from my /L loop is gone. The service can't start again, cause the %%n parameter already missing and my /L loop can't continue too -.-
Someone an idea what I can do to solve this problem?
Thank you already for reading this post.
Upvotes: 3
Views: 1476
Reputation: 130819
As MC ND said in his comment, issuing a GOTO within a FOR loop will break the loop. Actually, the issue is more general than that - issuing a GOTO within any block of code (paranthesized, or concatenated via &) will terminate the remainder of the block.
The simple solution is to extract the code that needs GOTO and put it in its own subroutine, and then CALL the routine from within your loop.
Set /p StartIP="Start IP (101):"
Set /p EndIP="End IP (199):"
for /L %%n IN (%StartIP%, 1, %EndIP%) DO (
psservice -u username -p password \\192.168.8.%%n stop 'ServiceName'
call :check %%n
psservice -u username -p password \\192.168.8.%%n start 'ServiceName'
)
exit /b
:CHECK
echo 5 sek.
ping 127.0.0.1 -n 5 > nul
for /F "tokens=3 delims=: " %%H in (
'psservice -u username -p password \\192.168.8.%1 query 'ServiceName' ^| findstr " STATE"'
) do (
echo.
echo state: %%H
if not %%H==STOPPED goto CHECK
)
exit /b
Upvotes: 3