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

如何通过Terraform变量向PowerShell脚本传递命名参数

Terraform变量传递至PowerShell脚本失败的解决方法

问题描述

通过Azure自定义脚本扩展部署时,尝试将Terraform变量传递给PowerShell脚本失败,报错提示param关键字未被识别。

相关代码

Terraform配置

resource "azurerm_virtual_machine_extension" "test" {
    name = "testt"
    virtual_machine_id = azurerm_virtual_machine.example.id
    publisher = "Microsoft.Compute"
    type = "CustomScriptExtension"
    type_handler_version = "1.9"            
    protected_settings = <<SETTINGS    
{    
"commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(file(\"shell.ps1\"))}')) | Out-File -filepath shell.ps1\" && powershell -ExecutionPolicy Unrestricted -File shell.ps1 -value1 ${var.value1} -value2 ${var.value2}"
    }    
SETTINGS    
}

PowerShell脚本(shell.ps1)

param(
  [string]$value1,
  [string]$value2
)

错误信息

"message": "param : 术语“param”未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后重试。"

问题原因

  1. 编码不匹配:Out-File默认使用UTF-16LE编码保存文件,PowerShell执行该编码的脚本时会解析失败,导致param无法被识别。
  2. 变量传递未加引号:如果var.value1或var.value2包含空格/特殊字符,会导致命令行参数拆分错误,破坏脚本执行逻辑。

修复方案

方案1:修正文件编码与变量引号

修改Terraform配置中的Out-File命令,添加-Encoding UTF8参数,并给变量值包裹单引号:

resource "azurerm_virtual_machine_extension" "test" {
    name = "testt"
    virtual_machine_id = azurerm_virtual_machine.example.id
    publisher = "Microsoft.Compute"
    type = "CustomScriptExtension"
    type_handler_version = "1.9"            
    protected_settings = <<SETTINGS    
{    
"commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(file(\"shell.ps1\"))}')) | Out-File -filepath shell.ps1 -Encoding UTF8\" && powershell -ExecutionPolicy Unrestricted -File shell.ps1 -value1 '${var.value1}' -value2 '${var.value2}'"
    }    
SETTINGS    
}

方案2:使用fileUris简化脚本部署

将PowerShell脚本上传至Azure存储账户(需配置公开访问或SAS权限),直接通过fileUris参数加载脚本,避免base64编码和文件写入步骤:

resource "azurerm_virtual_machine_extension" "test" {
    name = "testt"
    virtual_machine_id = azurerm_virtual_machine.example.id
    publisher = "Microsoft.Compute"
    type = "CustomScriptExtension"
    type_handler_version = "1.9"            
    settings = <<SETTINGS    
{    
"fileUris": ["https://your-storage-account.blob.core.windows.net/your-container/shell.ps1"],
"commandToExecute": "powershell -ExecutionPolicy Unrestricted -File shell.ps1 -value1 '${var.value1}' -value2 '${var.value2}'"
    }    
SETTINGS    
}

注意事项

  • 若变量值包含单引号,需提前在Terraform中进行转义(如replace(var.value1, "'", "''"))。
  • 建议使用较新的type_handler_version(如1.10及以上),提升兼容性和错误排查能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:15:11