使用 SC.exe 创建带参数的服务

Create service with arguments using SC.exe

在过去的 2 个小时里,我尝试了所有可能的方法来使用 sc.exe 创建服务并传递参数,但我似乎无法做到正确。

我已经阅读 this SO question 和所有答案大约 5 遍,但没有任何帮助!

从我在那里读到的内容来看,我似乎应该像这样构建命令:

sc create MyService binPath= "C:\path\to\myservice.exe --param1=TestString"

我的服务 OnStart 方法如下所示:

Protected Overrides Sub OnStart(ByVal args() As String)
    If Not IsNothing(args) Then
        Library.WriteLog("Number of args = " & args.Count)
        If args.Count > 0 Then
            For i = 0 To args.Count - 1
                Library.WriteLog("Arg" & i & ": " & args(i))
            Next
        End If
    End If
End Sub

但我尝试过的所有操作都在日志中产生 "Number of Args = 0"

为了清楚起见,我尝试了以下方法(可能还有一些):

sc create MyService binPath= "C:\path\to\myservice.exe --param1=TestString"
sc create MyService binPath= "C:\path\to\myservice.exe --TestString"
sc create MyService binPath= "C:\path\to\myservice.exe --param1=\"TestString\""
sc create MyService binPath= "C:\path\to\myservice.exe -param1=TestString"
sc create MyService binPath= "C:\path\to\myservice.exe -TestString"
sc create MyService binPath= "C:\path\to\myservice.exe -param1=\"TestString\""

我一定是漏掉了一些非常愚蠢的东西,但我正用它把头撞到墙上!

根据this answer and the commentsOnStartargs参数仅在windows服务对话框中手动设置启动参数时使用,无法保存。

您可以通过在 Main 方法(默认位于 Service.Designer.vb 文件中)访问它们来使用您正在设置的参数。下面是一个例子:

<MTAThread()> _
<System.Diagnostics.DebuggerNonUserCode()> _
Shared Sub Main(ByVal args As String())
    Dim ServicesToRun() As System.ServiceProcess.ServiceBase
    ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1(args)}
    System.ServiceProcess.ServiceBase.Run(ServicesToRun)
End Sub

您需要向您的服务添加或修改构造函数class以接受参数:

Private ReadOnly _arguments As String()

Public Sub New(ByVal args As String())
    InitializeComponent()
    _arguments = args
End Sub

那么你的OnStart方法就变成了:

Protected Overrides Sub OnStart(ByVal args() As String)
    If Not IsNothing(args) Then
        Library.WriteLog("Number of args = " & _arguments.Count)
        If args.Count > 0 Then
            For i = 0 To args.Count - 1
                Library.WriteLog("Arg" & i & ": " & _arguments(i))
            Next
        End If
    End If
End Sub