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

如何通过Terraform的Azure VMSS CustomScriptExtension传递两个PowerShell参数

解决Azure VMSS CustomScriptExtension传递多个PowerShell参数的问题

你之前用echo param1 | powershell -encodedCommand ...的方式是通过标准输入传参,这种方法仅适用于单参数场景,多参数时脚本无法正确拆分输入内容,导致传递失败。以下是两种可行的解决方式:

方案1:将脚本执行命令与参数一起编码

把调用脚本并传递参数的完整PowerShell命令进行Base64编码(PowerShell要求UTF-16LE编码),确保参数被正确传递:

resource "azurerm_virtual_machine_scale_set_extension" "runscript" {
  virtual_machine_scale_set_id = subid

  auto_upgrade_minor_version = true
  name                       = "RunCustomScript"
  publisher                  = "Microsoft.Compute"
  type                       = "CustomScriptExtension"
  type_handler_version       = "1.8"

  protected_settings = <<PROTECTED_SETTINGS
  {
    "commandToExecute" : "powershell -encodedCommand ${textencodebase64(<<EOF, "UTF-16LE")}
\$scriptBlock = [ScriptBlock]::Create(@'
${file("${path.module}/scripts/myscript.ps1")}
'@)
& \$scriptBlock "参数1" "参数2"
EOF
}"
  PROTECTED_SETTINGS
}

说明:

  • 先将本地脚本内容嵌入到PowerShell的Here-String中,转换为脚本块
  • 执行脚本块时直接传递多个位置参数,脚本中需用param($p1, $p2)定义参数接收逻辑

方案2:写入临时文件后执行(更直观)

把本地脚本内容写入VM的临时文件,再直接调用该文件并传递参数,适合复杂脚本场景:

resource "azurerm_virtual_machine_scale_set_extension" "runscript" {
  virtual_machine_scale_set_id = subid

  auto_upgrade_minor_version = true
  name                       = "RunCustomScript"
  publisher                  = "Microsoft.Compute"
  type                       = "CustomScriptExtension"
  type_handler_version       = "1.8"

  protected_settings = <<PROTECTED_SETTINGS
  {
    "commandToExecute" : "powershell -encodedCommand ${textencodebase64(<<EOF, "UTF-16LE")}
\$scriptContent = @'
${file("${path.module}/scripts/myscript.ps1")}
'@
\$tempScriptPath = Join-Path \$env:TEMP "myscript.ps1"
Set-Content -Path \$tempScriptPath -Value \$scriptContent -Encoding UTF8
& \$tempScriptPath "参数1" "参数2"
Remove-Item -Path \$tempScriptPath -Force
EOF
}"
  PROTECTED_SETTINGS
}

说明:

  • 将脚本写入临时文件后,完全模拟本地执行脚本的方式传递参数
  • 执行完成后删除临时文件,避免残留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:01:41