install4j:如何将命令行参数传递给windows服务

install4j:如何将命令行参数传递给windows服务,install4j,Install4j,我已经使用install4j创建了一个windows服务,并且一切正常,但是现在我需要将它的命令行参数传递给该服务。我知道我可以在新建服务向导中的服务创建时配置它们,但我希望将参数传递给注册服务命令ie: myservice.exe --install --arg arg1=val1 --arg arg1=val2 "My Service Name1" 或者将它们放入.vmoptions文件中,如: -Xmx256m arg1=val1 arg2=val2 这样做的唯一方法似乎是修改我的代码

我已经使用install4j创建了一个windows服务,并且一切正常,但是现在我需要将它的命令行参数传递给该服务。我知道我可以在新建服务向导中的服务创建时配置它们,但我希望将参数传递给注册服务命令ie:

myservice.exe --install --arg arg1=val1 --arg arg1=val2 "My Service Name1"
或者将它们放入.vmoptions文件中,如:

-Xmx256m
arg1=val1
arg2=val2

这样做的唯一方法似乎是修改我的代码,通过exe4j.launchName获取服务名称,然后加载具有该特定服务所需配置的其他文件或环境变量。我过去使用过其他java服务创建工具,它们都直接支持用户注册的命令行参数。

我知道你在一月份问过这个问题,但你有没有想过

我不知道你从哪里采购val1,val2等。用户是否在安装过程中将它们输入表单中的字段?假设他们是,那么这是一个类似的问题,我面临一段时间了

我的方法是使用一个可配置的表单,其中包含必要的字段(作为文本字段对象),并且显然将变量分配给文本字段的值(在文本字段的“用户输入/变量名称”类别下)

在后来的安装过程中,我有一个显示进度屏幕,上面附加了一个运行脚本操作,并使用一些java实现了我想要做的事情

以这种方式在install4j中选择设置变量时,有两个“陷阱”。首先,不管发生什么,都必须设置变量,即使它只是空字符串。因此,如果用户将某个字段留空(即他们不想将该参数传递给服务),您仍然需要为运行可执行文件或启动服务任务提供一个空字符串(稍后将详细介绍)。其次,参数不能有空格-每个空格分隔的参数都必须有自己的行

考虑到这一点,下面是一个运行脚本代码片段,它可能会实现您想要的:

final String[] argumentNames = {"arg1", "arg2", "arg3"};
// For each argument this method creates two variables. For example for arg1 it creates
// arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional.
// If the value of the variable set from the previous form (in this case, arg1) is not empty, then it will
// set 'arg1ArgumentIdentifierOptional' to '--arg', and 'arg1ArgumentAssignmentOptional' to the string arg1=val1 (where val1 
// was the value the user entered in the form for the variable).
// Otherwise, both arg1ArgumentIdentifierOptional and arg1ArgumentAssignmentOptional will be set to empty.
//
// This allows the installer to pass both parameters in a later Run executable task without worrying about if they're
// set or not.

for (String argumentName : argumentNames) {
    String argumentValue = context.getVariable(argumentName)==null?null:context.getVariable(argumentName)+"";
    boolean valueNonEmpty = (argumentValue != null && argumentValue.length() > 0);
    context.setVariable(
       argumentName + "ArgumentIdentifierOptional",
       valueNonEmpty ? "--arg": ""
    );
    context.setVariable(
       argumentName + "ArgumentAssignmentOptional",
       valueNonEmpty ? argumentName+"="+argumentValue : ""
    );    
}

return true;
最后一步是启动服务或可执行文件。我不太确定服务是如何工作的,但对于可执行文件,您可以创建任务,然后编辑“Arguments”字段,给它一个以行分隔的值列表

因此,在您的情况下,它可能如下所示:

--install
${installer:arg1ArgumentIdentifierOptional}
${installer:arg1ArgumentAssignmentOptional}
${installer:arg2ArgumentIdentifierOptional}
${installer:arg2ArgumentAssignmentOptional}
${installer:arg3ArgumentIdentifierOptional}
${installer:arg3ArgumentAssignmentOptional}
“我的服务名称1”

就这样。如果其他人知道如何更好地执行此操作,请随意改进此方法(这适用于install4j 4.2.8,顺便说一句)