安装Windows Service with Recovery操作以重新启动

Ray*_*Ray 82 .net service windows-services

我正在使用ServiceProcessInstallerServiceInstaller类安装Windows服务.

我已经用它ServiceProcessInstaller来设置启动类型,名称等.但是如何将恢复操作设置为重启?

我知道我可以在安装服务后手动执行此操作,方法是转到服务管理控制台并更改服务属性的恢复选项卡上的设置,但有没有办法在安装期间执行此操作?

服务属性恢复选项卡

Kev*_*vin 94

您可以使用sc设置恢复选项.以下将服务设置为在失败后重新启动:

sc failure [servicename] reset= 0 actions= restart/60000
Run Code Online (Sandbox Code Playgroud)

这可以很容易地从C#调用:

static void SetRecoveryOptions(string serviceName)
{
    int exitCode;
    using (var process = new Process())
    {
        var startInfo = process.StartInfo;
        startInfo.FileName = "sc";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;

        // tell Windows that the service should restart if it fails
        startInfo.Arguments = string.Format("failure \"{0}\" reset= 0 actions= restart/60000", serviceName);

        process.Start();
        process.WaitForExit();

        exitCode = process.ExitCode;
    }

    if (exitCode != 0)
        throw new InvalidOperationException();
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,语法可能看起来很奇怪,但`reset = 0`是正确的,而`reset = 0`是不正确的.正确使用空格是至关重要的,`reset =`是一个参数,后跟一个空格,然后是'0`. (20认同)
  • 如果您要在服务安装时从C#中的Installer []服务安装处理程序调用此函数,则可以将此调用插入到"Committed"事件处理程序中,该处理程序将在服务出现在Service Control Manager中之后立即执行.不要将它放在"AfterInstall"事件管理器中,因为这在第一次在盒子上安装服务时不起作用. (17认同)
  • 请注意,如果服务名称包含空格,则需要在引号中包含该名称. (4认同)

Jua*_*lez 11

经过多次尝试,我使用sc命令行应用程序解决了它.

我有使用installutil和sc的批处理文件.我的批处理文件类似于:

installutil.exe "path to your service.exe"
sc failure "your service name" reset= 300 command= "some exe file to execute" actions= restart/20000/run/1000/reboot/1000
Run Code Online (Sandbox Code Playgroud)

如果需要sc命令的完整文档,请单击此链接:SC.exe:与服务控制器和已安装的服务进行通信

注意:您需要在每个相等(=)符号后面添加一个空格.示例:reset = 300