使用Packer和PowerShell静默安装Matlab 2021b遇路径错误
解决Windows下Packer+PowerShell静默安装Matlab 2021b许可证复制失败问题
问题核心
Matlab安装程序返回Exit Code 0,但执行许可证文件复制时触发DirectoryNotFoundException,提示找不到路径C:\Tools\MATLAB\R2021b\licenses\license.lic。
根本原因分析
- 未等待安装进程完成:原脚本使用
Start-Process -PassThru后直接执行后续步骤,但Start-Process默认异步运行,此时安装可能仍在进行,目标目录尚未创建。 - licenses目录未自动生成:Matlab静默安装完成后,默认不会自动创建
licenses子目录,直接复制文件会因目录不存在报错。 - 环境变量未即时生效:
$env:MATLAB_ROOT可能在安装完成后未被即时加载,导致路径指向不准确。
修复方案
1. 强制等待安装进程结束
修改Start-Process命令,添加-Wait参数确保安装完成后再执行后续操作:
try { $process = Start-Process -FilePath ".\setup.exe" -ArgumentList "-inputFile $installer_input_path" -NoNewWindow -PassThru -Wait Write-Host "Exit code: $($process.ExitCode)" # 验证安装目录是否存在 if (-not (Test-Path -Path $env:MATLAB_ROOT)) { throw "Matlab安装目录不存在,安装可能未成功完成" } } catch { Write-Error "Error executing setup: $_" }
2. 提前创建licenses目录
在复制许可证文件前,先检查并创建目标目录:
# 先获取licenses目录路径,而非直接拼接文件路径 $matlab_license_folder = Join-Path $env:MATLAB_ROOT "licenses" # 检查目录是否存在,不存在则创建 if (-not (Test-Path -Path $matlab_license_folder)) { New-Item -ItemType Directory -Path $matlab_license_folder -Force | Out-Null } # 复制许可证文件到目录 Copy-Item -Path $license_file_path -Destination $matlab_license_folder -Force
3. 手动指定安装路径替代环境变量
如果$env:MATLAB_ROOT未即时生效,可直接使用和安装输入文件一致的路径:
# 替换为你的Matlab实际安装路径 $matlab_install_path = "C:\Tools\MATLAB\R2021b" $matlab_license_folder = Join-Path $matlab_install_path "licenses"
完整修复后的脚本
Write-Host "Starting MATLAB installation" # Run the MATLAB installer with the input file Write-Host "Running MATLAB installer. This might take some time..." if (Test-Path -Path $installer_input_path) { Write-Host "Found the installer input file at $installer_input_path" } else { Write-Host "Did not find the installer input file at $installer_input_path" throw "MATLAB installer input file not found" } try { $process = Start-Process -FilePath ".\setup.exe" -ArgumentList "-inputFile $installer_input_path" -NoNewWindow -PassThru -Wait Write-Host "Exit code: $($process.ExitCode)" # 验证安装目录 $matlab_install_path = "C:\Tools\MATLAB\R2021b" # 或使用$env:MATLAB_ROOT,确保路径正确 if (-not (Test-Path -Path $matlab_install_path)) { throw "Matlab installation directory not found at $matlab_install_path" } } catch { Write-Error "Error executing setup: $_" } # Copy the license file to the MATLAB licenses directory $matlab_license_folder = Join-Path $matlab_install_path "licenses" # 创建目录(如果不存在) if (-not (Test-Path -Path $matlab_license_folder)) { New-Item -ItemType Directory -Path $matlab_license_folder -Force | Out-Null } Copy-Item -Path $license_file_path -Destination $matlab_license_folder -Force Write-Host "MATLAB installation complete"
额外验证步骤
- 确认
matlab_installer_input.txt中的destinationFolder参数与脚本中使用的安装路径完全一致。 - 检查
$license_file_path指向的许可证文件确实存在且路径正确。
内容的提问来源于stack exchange,提问作者jtodić
相关产品推荐
相关产品推荐

