静默安装/卸载是一种安装/卸载形式,用户打开安装包后不显示任何安装界面,直接开始安装,支持使用命令行参数指定安装路径等。

1. 静默方式

常用的静默安装有 2 种:

  1. 在脚本中加入 SilentInstall 和 SilentUninstall 命令
  2. 在程序启动参数里加 /S 参数(区分大小写)

2. 当前是否静默运行

在脚本中判断安装、卸载程序是否为静默运行,可以使用 IfSilent

1
2
3
4
5
# 安装操作开始前.
Function .onInit
IfSilent +2 +1
MessageBox MB_ICONQUESTION|MB_OK "欢迎使用"
FunctionEnd

3. 默认应答

对于有些命令需要为静默安装指定默认的回答,如MessageBox需要加入/SD 开关来指定默认回答。

1
2
3
4
5
# 卸载操作开始前.
Function un.onInit
MessageBox MB_ICONQUESTION|MB_YESNO "确定要卸载吗?" /SD IDYES IDYES +2 IDNO +1
Abort
FunctionEnd

4. 启动参数解析

如果需要为静默安装指定其他的参数,如用户名等,可以使用程序启动参数指定,并在.onInit 函数里进行解析:

1
2
3
4
#使用插件FileFunc中的2个宏
!include "FileFunc.nsh"
!insertmacro GetParameters
!insertmacro GetOptions
1
2
# 定义全局变量
Var paramInstllDir # 启动参数-安装目录
1
2
3
4
5
6
7
8
# 自定义宏ParseParameters,在.onInit函数中调用即可
!macro ParseParameters
${GetParameters} $R0
${GetOptions} $R0 '/installdir' $R1
StrCpy $paramInstllDir $R1
IfSilent +1 +2
StrCpy $INSTDIR $paramInstllDir
!macroend