萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 電腦基礎知識 >  >> 電腦入門

Windows 服務安裝與移除命令速查:sc.exe、installutil、PowerShell 實戰

將執行檔 (exe) 註冊為 Windows 服務,或徹底移除殘留服務,常用於背景服務部署、開發測試、惡意軟體清理。本文整理三種主流工具的標準指令與參數說明。

方法一:sc.exe (原生服務控制管理器 CLI,最通用)

安裝服務

sc create "ServiceName" binPath= "C:\Full\Path\To\Service.exe" start= auto DisplayName= "顯示名稱" depend= "Tcpip/Afd"
  • binPath= **後必須有空格**,路徑含空格需雙引號包裹。
  • start=:auto (自動) / demand (手動) / disabled (停用) / delayed-auto (延遲自動)。
  • depend=:相依服務名稱,多個用 / 分隔。

啟動/停止/查詢/刪除

sc start "ServiceName"
sc stop "ServiceName"
sc query "ServiceName"
sc queryex "ServiceName"          :: 顯示 PID
sc config "ServiceName" start= delayed-auto  :: 修改啟動類型
sc delete "ServiceName"           :: **立即標記刪除**,需重開機或服務停止後完全移除

方法二:installutil.exe (.NET Framework 服務專用)

適用於繼承 System.ServiceProcess.ServiceBase 的 .NET 服務專案輸出 exe。

:: 安裝 (需管理員權限)
%windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe "C:\Path\MyService.exe"
:: 或 64-bit
%windir%\Microsoft.NET\Framework64\v4.0.30319\installutil.exe "C:\Path\MyService.exe"

:: 移除
installutil.exe /u "C:\Path\MyService.exe"

:: 安裝後自動啟動並設為自動
net start "ServiceName"
sc config "ServiceName" start= auto

專案需加入 ProjectInstaller (ServiceProcessInstaller + ServiceInstaller) 設定 Account=LocalSystem、StartType=Automatic。

方法三:PowerShell (現代化、物件導向、支援遠端)

# 建立服務 (需管理員)
New-Service -Name "ServiceName" -BinaryPathName "C:\Path\Service.exe" -DisplayName "顯示名稱" -StartupType Automatic -Description "說明"

# 啟動/停止/重啟
Start-Service "ServiceName"
Stop-Service "ServiceName"
Restart-Service "ServiceName"

# 查詢狀態
Get-Service "ServiceName" | Format-List *

# 修改啟動類型
Set-Service "ServiceName" -StartupType Automatic

# 移除服務 (需先停止)
Stop-Service "ServiceName"
Remove-Service "ServiceName"   # PowerShell 6.0+ / 7+
# 或舊版相容
sc.exe delete "ServiceName"
# 或直接操作登錄
Remove-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Services\ServiceName" -Recurse -Force

批次檔 (.bat) 一鍵部署範本

@echo off
set SVC_NAME=MyCustomService
set EXE_PATH=%~dp0MyService.exe

sc query "%SVC_NAME%" >nul 2>&1
if %errorlevel% equ 0 (
    echo 服務已存在,先停止並刪除...
    sc stop "%SVC_NAME%" >nul 2>&1
    timeout /t 2 >nul
    sc delete "%SVC_NAME%"
)

echo 安裝服務...
sc create "%SVC_NAME%" binPath= "\"%EXE_PATH%\"" start= auto DisplayName= "My Custom Service"
sc start "%SVC_NAME%"
echo 完成。按任意鍵結束...
pause

特殊情況處理

  • 服務名稱含空格:所有指令參數值必須用雙引號包裹。
  • 刪除後殘留「已標記為刪除」:服務仍在執行中,需 sc stop 後再 sc delete,或重開機完成移除。
  • 錯誤 1053/5 (拒絕存取/逾時):exe 非標準服務進入點 (缺少 ServiceMain)、權限不足 (需管理員)、路徑錯誤、相依服務未啟動。
  • 批次檔/腳本註冊為服務:需包裝器 (如 srvany.exe、nssm.exe、winsw) 將非服務程式轉為服務相容介面。

熟記 sc create/delete/query/config 四大金剛,加上 installutil 處理 .NET 服務,Windows 服務部署與清理不再手忙腳亂。

copyright © 萬盛學電腦網 all rights reserved