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

时间:2015-05-05 05:51:21

标签: windows-services

我花了最后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

但是我尝试的所有东西都会产生" 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\""

我必须在这里找到一些非常愚蠢的东西,但是我用它撞了一下墙!

1 个答案:

答案 0 :(得分:3)

根据this answer and the commentsargs OnStart参数仅在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

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

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
相关问题