Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Sp using command shell to start/stop services

Author  Topic 

phrankbooth
Posting Yak Master

162 Posts

Posted - 2012-12-09 : 14:27:44
I've written the sp below to start/stop windows services.

Can it be optimized any further and is the use of cmshell OK for this?


alter procedure spServiceController @Server varchar(250), @Command varchar(250), @Service varchar(250)
as
SET NOCOUNT ON

CREATE table #result(data varchar(100))


-- MSSQLServerOLAPService
declare
@SCCmd VARCHAR(1000) = ''' sc \\' + @Server + ' ' + @Command + ' ' + @Service + '''',
@State varchar(250) = CASE WHEN @Command = 'start' then 'RUNNING'
WHEN @Command = 'stop' then 'STOPPED'
END

EXEC ('exec master..xp_cmdshell ' + @SCCmd + ', ''no_output''' )

--Get Service Status
DECLARE @STATUS VARCHAR(100) = 'OTHER'
DECLARE @TimeOutInit datetime = current_timestamp

SET @SCCmd = ''' sc \\' + @Server + ' query ' + @Service + ' |find "STATE"'''

WHILE @STATUS <> @State AND DATEDIFF(SECOND, @TimeOutInit, current_timestamp) <= 120
BEGIN

EXEC ('INSERT INTO #result exec master..xp_cmdshell ' + @SCCmd)

SELECT TOP 1 @STATUS = CASE WHEN data like '%'+ @State +'%' THEN @State
ELSE @STATUS
END
FROM #result WHERE data IS NOT NULL AND data like '%'+ @State +'%'

END

SELECT 'SERVICE: ' + @Service + ' ON SERVER: ' + @Server + ' IS ' + @STATUS



--PhB
   

- Advertisement -