转换Array类型的ARM模板参数以在String[]类型的Powershell中使用



这里的目标是在windows防火墙中创建一个入站规则,使用单个powershell命令添加从模板参数中获取的多个远程地址。

我有一个类型为Array的参数vnAddressPrefixes,它包含地址前缀(如下默认值所示(。

"parameters": {
// ... Some more fields not relevant to this question
"vnAddressPrefixes": {
"defaultValue": [ "10.0.0.0/16", "10.0.0.0/24" ],
"type": "Array"
}
}

我有一个自定义脚本扩展(如下所示(,它运行powershell命令来在windows防火墙中创建入站规则,以添加多个远程地址

"resources": [
{
// ... Some more fields not relevant to this question
"type": "Microsoft.Compute/virtualMachines/extensions",
"properties": {
// ... Some more fields not relevant to this question
"publisher": "Microsoft.Compute",
"type": "CustomScriptExtension",
"protectedSettings": {
"commandToExecute": "[variables('commandToExecuteInVm')]"
}
}
}
]

变量CCD_ 2由参数CCD_。(我正在尝试将数组值从[10.0.0.0/16,10.0.0.0/24]转换为@("10.0.0.0/16","10.0.0.0/24")

"variables": {
// Variable for converting array to powershell format. Eg.: [10.0.0.0/16,10.0.0.0/24] to @("10.0.0.0/16","10.0.0.0/24")
"addressPrefixesTemp1": "[string(parameters('vnAddressPrefixes'))]", // Convert to string
"addressPrefixesTemp2": "[replace(variables('addressPrefixesTemp1'), '[', '@("')]", // Convert [ to @("
"addressPrefixesTemp3": "[replace(variables('addressPrefixesTemp2'), ',', '", "')]", // Convert , to ", "
"addressPrefixesTemp4": "[replace(variables('addressPrefixesTemp3'), ']', '")')]", // Convert ] to ")
// Variable for adding an inbound rule in windows firewall, for specific port, for accessing using application gateway fqdn
"addFirewallInboundRuleAllow8088": "[concat('New-NetFirewallRule -DisplayName Allow_Port_8088 -Direction Inbound -LocalPort 8088 -Protocol TCP -Action Allow -RemoteAddress ', variables('addressPrefixesTemp4'), ' ; ')]",
// Variable to store the final command to be executed in the VM
"commandToExecuteInVm": "[concat('powershell -ExecutionPolicy Unrestricted ', variables('addFirewallInboundRuleAllow8088'))]"
}

我收到以下错误,其中提到为RemoteAddress提供的值无效。

命令执行已完成,但由于返回非零的退出代码:"1"。该命令的错误输出为:'新NetFirewallRule:地址无效。地址可能是指定为IP地址、范围或子网。此外,以下内容某些地方允许使用地址关键字:LocalSubnet、DNS、,DHCP、WINS、DefaultGateway、Internet、Intranet、Intran…'了解更多信息信息,通过执行Get-AzVmssVm或获取AzVm(https://aka.ms/GetAzVm)。可以执行这些命令使用CloudShell(https://aka.ms/CloudShell)

看起来powershell需要转义双引号。因此,数组值应该从[10.0.0.0/16,10.0.0.0/24]转换为@("10.0.0.0/16","10.0.0.0/24")。(请注意,双引号是转义的(。

这意味着,必须在转义的双引号之前添加一个反斜杠(也应该转义(。

因此,"将变为\"

"variables": {
// Variable for converting array to powershell format. Eg.: [10.0.0.0/16,10.0.0.0/24] to @("10.0.0.0/16","10.0.0.0/24")
"addressPrefixesTemp1": "[string(parameters('vnAddressPrefixes'))]", // Convert to string
"addressPrefixesTemp2": "[replace(variables('addressPrefixesTemp1'), '[', '@(\"')]", // Convert [ to @("
"addressPrefixesTemp3": "[replace(variables('addressPrefixesTemp2'), ',', '\", \"')]", // Convert , to ", "
"addressPrefixesTemp4": "[replace(variables('addressPrefixesTemp3'), ']', '\")')]", // Convert ] to ")
}

请告诉我是否有其他更好的方法可以将类型为ArrayARM template参数转换为类型为String[]Powershell命令,而不必使用这些许多字符串操作。