Azure VM执行PowerShell脚本Run Command参数传递失败求助
解决Azure CLI执行PowerShell脚本参数为空的问题
问题原因
用az vm run-command invoke给Windows虚拟机上的PowerShell脚本传参时,直接写A=B不会自动映射到脚本里的$A变量——PowerShell脚本默认不会识别这种格式的参数,必须对应脚本的参数接收方式来传递。
具体解决办法
1. 把脚本改成支持命名参数
修改C:\Scripts\Start_script.ps1,开头加上参数定义:
param( [string]$A ) # 原脚本逻辑示例(追加日期和参数到日志) Get-Date | Out-File C:\Scripts\log.txt -Append "参数A的值: $A" | Out-File C:\Scripts\log.txt -Append
然后执行命令时,用--parameters传递命名参数:
az vm run-command invoke --resource-group <你的资源组名> --name <VM名称> --command-id RunPowerShellScript --scripts @C:\Scripts\Start_script.ps1 --parameters A=B
2. 通过环境变量传参(无需修改原脚本)
如果不想改动原脚本,直接在命令里先设置环境变量再调用脚本:
az vm run-command invoke --resource-group <你的资源组名> --name <VM名称> --command-id RunPowerShellScript --scripts '$env:A="B"; & C:\Scripts\Start_script.ps1'
脚本里直接用$env:A就能拿到参数值,比如原脚本中可以写:
Get-Date | Out-File C:\Scripts\log.txt -Append "参数A的值: $env:A" | Out-File C:\Scripts\log.txt -Append
3. 用位置参数传递
如果脚本适合用位置参数接收,直接传参数值,脚本里用$args数组获取:
脚本调整(或保持原逻辑,用$args[0]取参数):
Get-Date | Out-File C:\Scripts\log.txt -Append "参数值: $args[0]" | Out-File C:\Scripts\log.txt -Append
执行命令:
az vm run-command invoke --resource-group <你的资源组名> --name <VM名称> --command-id RunPowerShellScript --scripts @C:\Scripts\Start_script.ps1 --parameters "B"
内容的提问来源于stack exchange,提问作者Troy Shane
相关产品推荐
相关产品推荐

