如何通过AzureRm PowerShell在单条NSG规则中配置多个IP地址
解决Azure NSG单规则配置多个源IP的PowerShell问题
嗨,我之前也碰到过这个坑!Azure门户里用逗号分隔多个IP是前端帮你自动转成了数组格式,但PowerShell的Set-AzureRmNetworkSecurityRuleConfig cmdlet里的-SourceAddressPrefix参数不接受逗号拼接的单个字符串,它需要的是字符串数组,这就是你报错的核心原因。
这里给你两种简单的解决办法:
方法1:直接定义数组作为源IP前缀
直接把多个IP放进PowerShell数组里,格式用@("IP1", "IP2")就行,完整示例代码如下:
# 定义包含多个源IP的数组 $SourceAddressPrefix = @("x.x.x.x", "y.y.y.y") # 配置并应用NSG规则 Set-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name $name -Direction Inbound -Priority $priority -Access Allow -SourceAddressPrefix $SourceAddressPrefix -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange $destinationPortRange -Protocol TCP | Set-AzureRmNetworkSecurityGroup
方法2:将逗号分隔的字符串转换为数组
如果你手里已经有逗号分隔的IP字符串,可以用PowerShell的-split操作符把它拆成数组,示例:
# 原始逗号分隔的IP字符串(注意处理空格,这里是逗号加空格的格式) $ipListString = "x.x.x.x, y.y.y.y" # 把字符串拆分成数组 $SourceAddressPrefix = $ipListString -split ', ' # 执行规则配置 Set-AzureRmNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg -Name $name -Direction Inbound -Priority $priority -Access Allow -SourceAddressPrefix $SourceAddressPrefix -SourcePortRange * -DestinationAddressPrefix * -DestinationPortRange $destinationPortRange -Protocol TCP | Set-AzureRmNetworkSecurityGroup
额外提醒
- 务必保证
$priority的值在你的NSG里是唯一的,不然会覆盖现有规则或者触发报错 - 另外提一句:
AzureRm是旧版Azure PowerShell模块,微软现在推荐使用Az模块(对应cmdlet是Set-AzNetworkSecurityRuleConfig),如果之后升级模块,这个数组配置的逻辑是完全一致的,只是模块前缀从AzureRm换成Az就行
内容的提问来源于stack exchange,提问作者g.pickardou
相关产品推荐
相关产品推荐

