You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用msiexec传递变量失效,直接传字符串正常

问题原因

你遇到的问题源于PowerShell传递外部命令参数的解析逻辑差异:你构造的$key变量包含了额外的转义引号,PowerShell会将整个带引号的字符串作为单个参数传递给msiexec,但msiexec实际期望的是NKEY=1234567890这种格式(或由PowerShell自动处理参数的引号包裹),多余的外层引号导致参数无法被正常识别。

解决方法

方案1:简化参数变量构造

修改$key的赋值方式,去掉多余的转义引号(适用于密钥无空格/特殊字符的场景):

param(
  [String]$SITESECRETKEY
)
$key = "NKEY=$SITESECRETKEY"
$msiPath = "C:\temp\DNS_Agent_Setup.msi"

Invoke-WebRequest -Uri "https://download.dnsfilter.com/User_Agent/Windows/DNS_Agent_Setup.msi" -OutFile $msiPath
msiexec /qn /i $msiPath $key

若密钥包含空格或特殊字符,可保留引号但无需转义外层:

$key = "NKEY=`"$SITESECRETKEY`""

方案2:使用Start-Process传递参数数组(推荐,更可靠)

Start-Process可明确将每个参数作为独立元素传递,避免解析歧义,还能等待安装完成、获取执行状态:

param(
  [String]$SITESECRETKEY
)
$msiPath = "C:\temp\DNS_Agent_Setup.msi"

Invoke-WebRequest -Uri "https://download.dnsfilter.com/User_Agent/Windows/DNS_Agent_Setup.msi" -OutFile $msiPath

$arguments = @(
  "/qn",
  "/i",
  "`"$msiPath`"",
  "NKEY=`"$SITESECRETKEY`""
)

Start-Process -FilePath msiexec -ArgumentList $arguments -Wait -NoNewWindow

-Wait会让脚本等待安装完成,-NoNewWindow避免弹出额外命令行窗口。

方案3:使用调用运算符&直接展开参数

若习惯直接调用命令,可通过调用运算符确保参数正确展开:

param(
  [String]$SITESECRETKEY
)
$msiPath = "C:\temp\DNS_Agent_Setup.msi"

Invoke-WebRequest -Uri "https://download.dnsfilter.com/User_Agent/Windows/DNS_Agent_Setup.msi" -OutFile $msiPath

& msiexec /qn /i "`"$msiPath`"" "NKEY=`"$SITESECRETKEY`""

内容的提问来源于stack exchange,提问作者user208160

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:42:37