PowerShell脚本执行报错:表达式或语句中存在意外Token ':'
问题解决:ARM模板自定义脚本扩展报错“表达式或语句中的token ':'”
错误原因分析
dependsOn格式错误:ARM模板中依赖项必须通过resourceId函数引用资源,直接写资源名称会被当成无效表达式解析。- PowerShell变量未转义:ARM模板引擎会解析字符串中的
$符号,导致PowerShell的$env:computername和子表达式$()被错误识别,引发语法错误。 - 布尔值写法错误:ARM JSON中的布尔值不需要加
$,$true是PowerShell语法,不符合JSON规范。
修正后的完整脚本
{ "type": "Microsoft.Compute/virtualMachines/extensions", "name": "az104-08-vm1/customScriptExtension", "apiVersion": "2018-06-01", "location": "[resourceGroup().location]", "dependsOn": "[resourceId('Microsoft.Compute/virtualMachines', 'az104-08-vm0')]", "properties": { "publisher": "Microsoft.Compute", "type": "CustomScriptExtension", "typeHandlerVersion": "1.7", "autoUpgradeMinorVersion": true, "settings": { "commandToExecute": "powershell.exe Install-WindowsFeature -name Web-Server -IncludeManagementTools && powershell.exe remove-item 'C:\\inetpub\\wwwroot\\iisstart.htm' && powershell.exe Add-Content -Path 'C:\\inetpub\\wwwroot\\iisstart.htm' -Value $$('Hello World from ' + $$env:computername)" } } }
关键修改说明
dependsOn修正:使用resourceId函数生成正确的资源依赖ID,确保ARM能正确识别依赖的虚拟机。- PowerShell变量转义:将所有PowerShell中的
$替换为$$,避免ARM模板引擎错误解析这些变量,让PowerShell能正确读取环境变量和执行子表达式。 - 布尔值修正:将
$true改为JSON标准的true,符合ARM模板的语法要求。
内容的提问来源于stack exchange,提问作者Tanmay Kanungo
相关产品推荐
相关产品推荐

