將執行檔 (exe) 註冊為 Windows 服務,或徹底移除殘留服務,常用於背景服務部署、開發測試、惡意軟體清理。本文整理三種主流工具的標準指令與參數說明。
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" :: **立即標記刪除**,需重開機或服務停止後完全移除
適用於繼承 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。
# 建立服務 (需管理員)
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
@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,或重開機完成移除。srvany.exe、nssm.exe、winsw) 將非服務程式轉為服務相容介面。熟記 sc create/delete/query/config 四大金剛,加上 installutil 處理 .NET 服務,Windows 服務部署與清理不再手忙腳亂。