Stop a service on Remote server

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
sri
Posts: 6
Joined: 05 Aug 2008 19:11

Stop a service on Remote server

#1 Post by sri » 13 Aug 2009 02:06

Hi All

I would like to stop a windows service remotely and wait until the service stops before proceeding to the next line of code. In other words, To write a batch code to stop services with dependencies, One service should stop completely before stopping the second one.

The code that i have written does stop the services but it is not waiting for the first service to stop before it stops the second one. Can someone please shed some light on this

Code: Select all

@echo off
set server=servername
set winservice1=service1
set winservice2=service2

cls
echo Stopping service %winservice1% for server %server%...

REM STOP WINSERVICE1
sc \\%server%  stop  %winservice1%  | findstr STATE
sc \\%server%  query %winservice1%  | findstr STATE | findstr STOPPED > NUL

if errorlevel 1 (
   set output=Error while stopping service1 :(
   goto end
)

echo Stopping service %winservice2% for server %server%...

REM STOP WINSERVICE2
sc \\%server%  stop  %winservice2%  | findstr STATE
sc \\%server%  query %winservice2%  | findstr STATE | findstr STOPPED > NUL

if errorlevel 1 (
   set output=Error while stopping service2 :(
   goto end
)

goto end
:end
echo %output%


thanks for your help

DccD
Posts: 23
Joined: 26 Aug 2009 19:34

#2 Post by DccD » 26 Aug 2009 22:10

You might need to add some time between the stop command is sent and the query for state:

Code: Select all

ping -n 3 127.0.0.1 >nul


Or better use a FOR loop and test the state of the service before going on:

Code: Select all

FOR %%A IN ("%winservice1%", "%winservice2%", "%winservice3%") DO call :stopsvc %%~A
goto end

:stopsvc
set svcstatus=
echo Stopping "%1"...
sc \\%server% stop %1 >nul
:checkstate
ping -n 2 127.0.0.1 >nul
FOR /F "tokens=3 delims=: " %%B IN ('sc \\%server% query %1 ^|find "STATE"') DO set svcstatus=%%B
if %svcstatus% NEQ STOPPED goto checkstate
goto :EOF

:end


Hope it helps :)

Post Reply