Dot-Net

使用 InstallUtil 解除安裝不存在的服務

  • February 5, 2013

我正在使用我的服務的建構前和建構後事件來解除安裝和安裝服務。唯一的問題是,另一個開發人員第一次使用預建構事件時它會失敗,因為該服務尚未安裝。

我目前解除安裝的預建構事件是

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

當服務已經安裝時,我如何才能使用它來解除安裝?

您可以使用 Microsoft SC 工具 (Sc.exe) 來查詢服務的狀態,甚至可以創建或刪除服務。這裡有一篇關於這個命令使用的文章:http: //support.microsoft.com/kb/251192

從命令提示符視窗(為強調而編輯的內容):

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).

執行此命令來查詢 (A) 存在且 (B) 不存在的服務會導致:

(一個)

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

(乙)

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

The specified service does not exist as an installed service.

因此,您可以在嘗試使用以下命令刪除服務之前測試它是否存在——(請原諒對 FOR 語句的排斥使用,我不確定如何將 sc 命令的輸出擷取到變數中或在 IF 語句中使用它)-

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%

引用自:https://stackoverflow.com/questions/4019795