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

Posted

技术标签:

【中文标题】sc安装后如何自动启动windows服务?【英文标题】:How to autostart windows service after install by sc? 【发布时间】:2017-08-26 22:41:28 【问题描述】:

我创建了一个用于安装服务的批处理文件,因为我需要在没有 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函数中的代码不起作用?

【问题讨论】:

【参考方案1】:

这可以通过使用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

【讨论】:

这很简单。也许,我使用了错误的关键字搜索。但这意味着我在 afterInstall 函数中的代码在使用 sc 安装时不起作用?【参考方案2】:

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

服务存在于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

【讨论】:

以上是关于sc安装后如何自动启动windows服务?的主要内容,如果未能解决你的问题,请参考以下文章

wind 开启远程访问

如何在Windows下卸载重装Mysql

windows sc使用方法之一

用sc create 创建的Tomcat服务不能启动 报错:1053

安装 C# 后,无法使用 WPF App 使用 SC.exe 创建 Windows 服务

如何在安装后启动Topshelf服务?