views:

41

answers:

1

I'm using pre and post build events of my service to uninstall and install the service. The only problem is that the first time another developer uses the pre build event it fails since the service is not yet installed.

My current pre build event which uninstalls is

%WinDir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /u $(TargetPath)

How can i use this to ONLY uninstall when the service already installed?

+3  A: 

You can use the Microsoft SC tool (Sc.exe) to query the status of a service or even create or delete one. Here is an article on the use of this command: http://support.microsoft.com/kb/251192

From a Command Prompt window (content edited for emphasis):

C:\windows\system32>sc
DESCRIPTION:
        SC is a command line program used for communicating with the
        Service Control Manager and services.
USAGE:
        sc <server> [command] [service name] <option1> <option2>...

       The option <server> has the form "\\ServerName"
       Further help on commands can be obtained by typing: "sc [command]"
       Commands:
         query-----------Queries the status for a service, or
                         enumerates the status for types of services.
         queryex---------Queries the extended status for a service, or
                         enumerates the status for types of services.
         start-----------Starts a service.
         pause-----------Sends a PAUSE control request to a service.
         continue--------Sends a CONTINUE control request to a service.
         stop------------Sends a STOP request to a service.
         delete----------Deletes a service (from the registry).
         create----------Creates a service. (adds it to the registry).

Running this command to query a service that (A) exists and (B) does not exist results in:

(A)

C:\Windows\System32>sc query W32Time

SERVICE_NAME: W32Time
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 1  STOPPED
        WIN32_EXIT_CODE    : 1077  (0x435)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

(B)

C:\Windows\System32>sc query nothere
[SC] EnumQueryServicesStatus:OpenService FAILED 1060:

The specified service does not exist as an installed service.

So, you could test for the existence of a service before attempting to delete it using the following -- (pardon the repulsive use of the FOR statement, I'm not exactly sure how to capture the output of the sc command into a variable or use it in an IF statement) --

set svcname=W32Time
set svc=exists
for /f "delims=" %%o in ('sc query %svcname% ^| find "FAIL"') do set svc=notexists

if "%svc%"=="exists" sc delete %svcname%
dh0well
I had play around with stopping and starting the service for this to work but other wise it was perfect. Thanks
g.foley
:) glad that worked for you
dh0well