You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure NSG脚本故障:删除RDP规则后无法重新添加

问题分析与解决

核心问题

你的脚本无法添加规则的原因主要有两点:

  1. Add-AzNetworkSecurityRuleConfig未关联到当前遍历的NSG对象,直接管道到Set-AzNetworkSecurityGroup缺少必要的NSG上下文。
  2. 修改NSG后未更新本地的$nsg对象,后续操作使用的是旧的对象状态。

另外还有一处语法错误:变量定义nsgs = Get-AzNetworkSecurityGroup缺少PowerShell变量前缀$,正确写法应为$nsgs = Get-AzNetworkSecurityGroup。

修正后的脚本

$nsgs = Get-AzNetworkSecurityGroup
foreach ($nsg in $nsgs) {
    # 遍历并删除名称含"Allow-RDP"的规则
    $nsgRules = Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg 
    foreach ($nsgRule in $nsgsRules) { 
        if ($nsgRule.Name -like "*Allow-RDP") {
            Write-Host "移除规则: $($nsgRule.Name) (所属NSG: $($nsg.Name))"
            Remove-AzNetworkSecurityRuleConfig -Name $nsgRule.Name -NetworkSecurityGroup $nsg 
        } 
    } 

    # 保存删除规则后的NSG配置,同时更新本地$nsg对象
    $nsg = $nsg | Set-AzNetworkSecurityGroup

    # 检查优先级200是否已被占用,避免冲突
    $existingPriorityRule = Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg | Where-Object { $_.Priority -eq 200 }
    $targetPriority = 200
    if ($existingPriorityRule) {
        Write-Warning "NSG $($nsg.Name)中优先级200已被规则$($existingPriorityRule.Name)占用,自动调整优先级"
        # 找到下一个可用的优先级
        while (Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg | Where-Object { $_.Priority -eq $targetPriority }) {
            $targetPriority++
        }
    }

    # 添加新的RDP规则到当前NSG
    $nsg = Add-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg `
        -Name "Allow-RDP" -Description "Allow RDP" -Access Allow `
        -Protocol Tcp -Direction Inbound -Priority $targetPriority `
        -SourceAddressPrefix Internet -SourcePortRange * `
        -DestinationAddressPrefix * -DestinationPortRange 3389

    # 保存添加规则后的配置
    $nsg | Set-AzNetworkSecurityGroup
    Write-Host "已为NSG $($nsg.Name)添加Allow-RDP规则(优先级: $targetPriority)"
}

关键修正点

  • 每次修改NSG(删除/添加规则)后,将Set-AzNetworkSecurityGroup的输出重新赋值给$nsg,确保后续操作基于最新的NSG对象。
  • Add-AzNetworkSecurityRuleConfig必须通过-NetworkSecurityGroup参数明确指定目标NSG,修改后的对象需保存后再提交更改。
  • 增加了优先级冲突检查,自动调整到可用的优先级,避免因优先级重复导致添加失败。

内容的提问来源于stack exchange,提问作者HiRabba40

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:12:53