Restart a service remotely

Just being asked by a few guys to have a script to restart a service remotely.

Below is the example of source code to restart a “SMS Agent Host” service from a computer called “ABC-D-1234” 
===================================================== 
Dim strComputer
Dim strServiceName 

strComputer = “ABC-D-1234”
strServiceName =  “CcmExec”

 ‘// Stop Service  
StartWin32Service strComputer, strServiceName, False

 ‘// Pause to allow service to stop  
Wscript.Sleep 5000

 ‘// Start Service  
StartWin32Service strComputer, strServiceName, True

Sub StartWin32Service(vComputer, vServiceName, bStart)
    Dim strWQL
    Dim objWMIService
    Dim colWinServiceSet
    Dim objWinService
    Dim intRetVal

    On Error Resume Next
 
    Set objWMIService = GetObject(“winmgmts:\\” & vComputer & “\root\cimv2”)
    If Err <> 0 Then
        Wscript.Echo “Connect to ” & vComputer & ” failed.”
        Err.Clear
        Exit Sub
    End If

    strWQL = “SELECT * FROM Win32_Service”
    strWQL = strWQL & ” WHERE Name = ‘” & vServiceName & “‘”
    Set colWinServiceSet = objWMIService.ExecQuery(strWQL)

    If colWinServiceSet.Count > 0 Then

        For Each objWinService in colWinServiceSet

            If bStart = True Then  ‘// Start Service 
           
                If objWinService.Started = False Then ‘// If Service is in Stop status
                    intRetVal = objWinService.StartService
                    If intRetVal = 0 Then 
                        Wscript.Echo “Start ” & vServiceName  & ” successful.”
                    Else
                        Wscript.Echo “Start ” & vServiceName & ” failed.”   
                    End If
                Else ‘// If Service is in Start status
                    Wscript.Echo vServiceName & ” already started.”
                End If

            Else  ‘// Stop Service
          
                If objWinService.Started = True Then ‘// If Service is in Start status
                    intRetVal = objWinService.StopService
                    If intRetVal = 0 Then
                         Wscript.Echo “Stop ” & vServiceName & ” successful.”
                    Else
                         Wscript.Echo “Stop ” & vServiceName & ” failed.”
                    End If
                Else ‘// If Service is in Stop status
                     Wscript.Echo vServiceName & ” already stopped.”
                End If

            End If

        Next

    Else

         Wscript.Echo vServiceName & ” not found.”

    End If

    Set objWMIService = Nothing
End Sub
=====================================================
To use it, copy the script to a notepad and name it as <name>.vbs. Then, run it from the command prompt using this command: cscript <name>.vbs.

Advertisements

About this entry