管理 Windows 自定义服务(Windows Service)
在 Windows 系统中,你可以使用 sc.exe
命令或者 PowerShell 来创建自定义服务。以下是两种方法:
使用 sc.exe
命令:
-
打开命令提示符(以管理员身份运行)。
-
使用
sc.exe
命令创建服务,语法如下:
sc create <ServiceName> binPath= "<Path to Executable>" DisplayName= "<DisplayName>" start= <StartType>
<ServiceName>
:为服务指定的服务名。<Path to Executable>
:服务运行的可执行文件的路径。<DisplayName>
:显示的服务名称。<StartType>
:服务的启动类型,可以是auto
、demand
或者disabled
。
注意:等号前不能有空格,等号后必须有空格
例如:
sc create MyService binPath= "C:\Path\To\MyService.exe" DisplayName= "MyService" start= auto
- 执行完成后,服务就会被创建。
- 使用
sc.exe
命令查询服务,语法如下:
sc query <ServiceName>
- 使用
sc.exe
命令启动服务,语法如下:
sc start <ServiceName>
- 使用
sc.exe
命令停止服务,语法如下:
sc stop <ServiceName>
- 使用
sc.exe
命令删除服务,语法如下:
sc delete <ServiceName>
注意:先将服务停止再删除。
有时服务删除成功后,在服务列表还存在该服务,但服务启动类型已变更为禁用,通过 sc
命令再次删除却提示 [SC] DeleteService 失败 1072: 指定的服务已标记为删除。
时,这时可以通过注册表进行删除,到注册表中找 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
,然后找到对应的 ServiceName
进行删除。