寻求批量部署用PowerShell MSI静默安装脚本解决方案
修正后的MSI静默安装PowerShell脚本(批量部署2FA专用)
原脚本核心问题分析
- 误用批处理语法
%~dp0:PowerShell不识别该变量,导致MSI路径被解析为字面量,触发Windows Installer参数提示窗口 - 日志路径不一致:Desktop和Laptop分支的共享日志路径不同,易引发维护混乱
- 动作不符合需求:原脚本最后执行的是锁定工作站,而非要求的用户注销
- 未验证安装结果:无法确保安装成功后再执行后续操作,批量部署风险高
修正后的完整脚本
# 定义统一的共享日志文件路径 $logFile = "\\XXX\XXX\XXX\XXX\Log\$env:Computername.txt" # 获取脚本所在目录,替代批处理的%~dp0 $scriptDir = $PSScriptRoot # 拼接MSI安装包和本地日志路径 $msiFilePath = Join-Path -Path $scriptDir -ChildPath "setup.msi" $installLog = Join-Path -Path $scriptDir -ChildPath "setup.log" # 判断设备类型(台式机/笔记本) $deviceType = (Get-ComputerInfo).CsPCSystemType if ($deviceType -match "Desktop") { "Desktop Configuration was used." | Out-File -FilePath $logFile -Append -Encoding UTF8 } else { "Laptop Configuration was used." | Out-File -FilePath $logFile -Append -Encoding UTF8 } # 执行完全静默的MSI安装 $msiexecParams = "/i `"$msiFilePath`" /qn /norestart /L*v `"$installLog`"" Start-Process msiexec.exe -ArgumentList $msiexecParams -Wait # 根据msiexec退出码判断安装结果 switch ($LASTEXITCODE) { 0 { "Installation succeeded (no restart needed). Logging off user." | Out-File -FilePath $logFile -Append -Encoding UTF8 # 注销当前用户 shutdown.exe /l } 3010 { "Installation succeeded (restart required later). Logging off user." | Out-File -FilePath $logFile -Append -Encoding UTF8 shutdown.exe /l } default { "Installation failed with exit code: $LASTEXITCODE" | Out-File -FilePath $logFile -Append -Encoding UTF8 } }
关键修改说明
- 路径变量替换:用PowerShell原生的
$PSScriptRoot获取脚本所在目录,配合Join-Path生成合法路径,彻底解决批处理语法兼容性问题 - 统一日志路径:将两个分支的日志写入同一共享路径,方便后续批量排查
- 完全静默参数:把
/passive改为/qn,实现完全无界面安装(/passive会显示进度条,不符合大规模静默部署需求) - 安装结果校验:通过
$LASTEXITCODE捕获msiexec退出码,0为成功无需重启,3010为成功但需重启(因加了/norestart),仅在成功时执行注销 - 修正注销动作:用
shutdown.exe /l执行用户注销,替代原脚本的锁定工作站命令
内容的提问来源于stack exchange,提问作者user17871699
相关产品推荐
相关产品推荐

