使用PowerShell向Azure NSG指定规则中添加IP地址的实现方法问询
实现方法
前置要求
- 已安装Az.Network PowerShell模块
- 已完成Azure账号登录,且切换到目标NSG所在的订阅
具体实现脚本
你之前使用的Add-AzNetworkSecurityRuleConfig是新增NSG规则的命令,要修改现有规则的IP列表,直接读取现有规则配置、追加IP后更新即可,完整可运行脚本如下:
# 自定义配置参数 $nsgName = "blabla-test" $resourceGroupName = "blabla" $targetRuleName = "blabla" # 支持单个IP、CIDR格式,多个地址用逗号分隔 $newIpList = @("1.2.3.4", "5.6.7.0/24") # 1. 获取目标NSG实例 $nsg = Get-AzNetworkSecurityGroup -Name $nsgName -ResourceGroupName $resourceGroupName # 2. 读取要修改的封禁规则现有配置 $rule = $nsg | Get-AzNetworkSecurityRuleConfig -Name $targetRuleName # 3. 合并现有IP和新增IP,自动去重避免报错 $updatedSourceAddress = $rule.SourceAddressPrefix + $newIpList | Select-Object -Unique # 4. 更新规则配置,保留原规则的其他参数不变 $nsg | Set-AzNetworkSecurityRuleConfig -Name $targetRuleName ` -Access $rule.Access ` -Protocol $rule.Protocol ` -Direction $rule.Direction ` -Priority $rule.Priority ` -SourceAddressPrefix $updatedSourceAddress ` -SourcePortRange $rule.SourcePortRange ` -DestinationAddressPrefix $rule.DestinationAddressPrefix ` -DestinationPortRange $rule.DestinationPortRange # 5. 提交修改到Azure生效 $nsg | Set-AzNetworkSecurityGroup
验证与注意事项
- 执行完成后可以用你之前的查询命令验证IP是否添加成功:
(Get-AzNetworkSecurityGroup -name $nsgName | Get-AzNetworkSecurityRuleConfig -name $targetRuleName).SourceAddressPrefix - 单条NSG规则默认最多支持1000个IP/CIDR条目,超出限制需要拆分到多条规则实现
- 批量添加大量IP时建议先整理好所有IP再统一更新,减少API调用次数避免触发限流
内容的提问来源于stack exchange,提问作者Shahar
相关产品推荐
相关产品推荐

