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

时间:2012-01-06 14:13:02

标签: install4j

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

myservice.exe --install --arg arg1=val1 --arg arg1=val2 "My Service Name1"

或将它们放在.vmoptions文件中,如:

-Xmx256m
arg1=val1
arg2=val2

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

1 个答案:

答案 0 :(得分:1)

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

我不知道你从哪里采购val1,val2等。用户是否在安装过程中将其输入到表单中的字段中?假设它们是,那么这与我前面遇到的问题类似。

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

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

当以这种方式选择在install4j中设置变量时,有两个'陷阱'。首先,无论如何都要设置变量HAS,即使它只是空字符串。因此,如果用户将字段留空(即他们不想将该参数传递给服务),您仍然需要为Run可执行文件或Launch Service任务提供一个空字符串(稍后会更多) )其次,参数不能有空格 - 每个空格分隔的参数都必须有自己的行。

考虑到这一点,这是一个可以达到你想要的运行脚本代码片段:

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,顺便说一句)。