SYSK 197: Smart Start and Stop Service in VS.NET Build

If you have a windows service project as part of your solution, you’re quite familiar with the issues it presents — if the service is running and you’re recompiling either the service project itself, or any assemblies loaded by the service, you’ll get a build error.  The script below, courtesy of Scott Jennings, is a way to stop and start service, if it’s installed and is running/stopped correspondingly.  All that remains to do it to add the script invocation code to pre-build and post-build event command lines in Visual Studio.

‘ Usage:

       start /w wscript “<path>\ServiceHelper.vbs” <start|stop> <servicename>

‘ Example:

       start /w wscript “C:\Projects\XYZ\ServiceHelper.vbs” start myservice


Dim WMIService

Dim Services

Dim Service

Dim action

Dim result


If Wscript.Arguments.Count <> 2 Then

            Wscript.Echo “Usage: ServiceHelper.vbs start|stop ServiceName”

            Wscript.Quit 1

End If


Set WMIService = GetObject(“winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2”)


Set Services = WMIService.ExecQuery(“Select * from Win32_Service where Name = ‘” + Wscript.Arguments(1) + “‘”)


If Services.Count > 1 Then

            Wscript.Echo “More than one matching service”

            Wscript.Quit 1

ElseIf Services.Count = 1 Then

    action = Wscript.Arguments(0)


    For Each Service In Services

        If action = “start” AND Service.State <> “Running” Then

            result = Service.StartService()

        ElseIf action = “stop” AND Service.State <> “Stopped” Then

            result = Service.StopService()

        End If       





    Wscript.Echo “No such service found”

    Wscript.Quit 1

End If


Special thanks to Scott Jennings who created this solution!


Comments (0)