如何在 sc 安装后自动启动 windows 服务?

How to autostart windows service after install by sc?

我创建了一个用于安装服务的批处理文件,因为我需要在没有 Visual Studio.

的 PC 上安装我的服务

批处理文件内容:

@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
echo Installing service complete
pause

而且我需要在安装后自动启动 MyService,所以我编写了以下代码:

private void svInstaller_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController(svInstaller.ServiceName);
    sc.Start();
}

如果我通过 Visual Studio 命令提示符和 InstallUtil 安装我的服务,没有任何问题。 当我通过批处理文件安装服务时,我的服务没有自动启动。

如何在通过批处理文件安装后自动启动我的服务?

更新:感谢Sam Denty的回答,我的问题已经解决了。
但我还有一个问题:当我通过sc安装我的服务时,我在AfterInstall函数中的代码不起作用?

这可以通过使用 net start servicesc start 命令 (see previous question on that) 来实现。

要使用sc start启动服务,语法是:

sc [<ServerName>] start <ServiceName> [<ServiceArguments>]

<ServerName>
    Specifies the name of the remote server on which the service is located. The name must use the Universal Naming Convention (UNC) format (for example, \myserver). To run SC.exe locally, omit this parameter.
<ServiceName>
    Specifies the service name returned by the getkeyname operation.
<ServiceArguments>
    Specifies the service arguments to pass to the service to be started.

示例:

sc start MyService


更新脚本:

@echo OFF
echo Installing service...
sc create "MyService" binpath= %~dp0\MyService.exe start= auto
sc start MyService
echo Installing service complete
pause

您可以安装服务,使其在操作系统启动时自动启动。

服务已存在于 HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services 键中。

Start 子键决定服务 运行 和时间。

适用于内核驱动程序的最低可能值:

0 - Boot:由内核加载程序加载。引导(启动)卷的驱动程序堆栈组件必须由内核加载程序加载。

1 - 系统:由I/O子系统加载。指定驱动程序在内核初始化时加载。

2 - 自动:由服务控制管理器加载。指定自动加载或启动服务。

auto”选项(“2”值)似乎是您的最佳选择。

以下是调用

的选项
SC CREATE

因此,如果 运行 您问题中的命令,

sc create "MyService" binpath= %~dp0\MyService.exe start= auto

由于您指定了 "start = auto",因此您无需执行任何其他操作,因为该服务会自动启动。

关于空格问题,试试这个:

SET servicebin=several words.exe
sc create "MyService""%servicebin%" start = auto