0

I'm trying to automate my NSG rules and find out wrong nsg rules. here I'm trying to find the source Ip address is added or not but the code getting executed and deleting the rules even if the IP addresses are available.

$nsg = Get-AzNetworkSecurityGroup  -ResourceGroupName Testingday4
$nsgRules = Get-AzNetworkSecurityRuleConfig -NetworkSecurityGroup $nsg
foreach($nsgRule in $nsgRules)
{
    if($nsgRule.Direction -eq "inbound" -and {$_.DestinationPortRange -eq -split ('') -or $_.DestinationAddressPrefix -ne $null}){
        $nsgRule.Name
        Remove-AzNetworkSecurityRuleConfig -Name $nsgRule.Name -NetworkSecurityGroup $nsg
    }    }

$nsg | Set-AzNetworkSecurityGroup
bunny
  • 1

1 Answers1

0

I tried to reproduce in my environment to delete the rule which haves source address prefix of value for example "10.0.0.0/24". I could remove that NSG rule successfully using below Power Shell Script

(https://i.imgur.com/PosR5Vw.png)

Run below script to delete the specific source IP prefix

Get-AzSubscription
Set-AzContext -SubscriptionId "Subscription ID"
$RGname="Resource Group Name"
$nsgname="NSG Name"
$nsg = Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname
$nsgRules = Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname
#$ruleNames = $nsgRules.SecurityRules.Name
#$rulesrcaddpre = $nsgRules.SecurityRules.SourceAddressPrefix
foreach($rule in $nsgRules)
{
    $rname = $rule.SecurityRules.Name
    $raddpre = $rule.SecurityRules.SourceAddressPrefix 
    if($raddpre -eq "10.0.0.0/24")
    {
    #AzNetworkSecurityRuleConfig -Name AllowInternetOutBound

      Remove-AzNetworkSecurityRuleConfig -Name $rname -NetworkSecurityGroup $nsg
    }  
}
$nsg | Set-AzNetworkSecurityGroup

Rule got delete after the execute the script.

(https://i.imgur.com/eL7xR3U.png)

In order to create the rule with PowerShell use below Script

# Add the inbound security rule.
$nsg | Add-AzNetworkSecurityRuleConfig -Name $rulename -Description "Allow app port" -Access Allow `
    -Protocol * -Direction Inbound -Priority 3891 -SourceAddressPrefix "*" -SourcePortRange * `
    -DestinationAddressPrefix * -DestinationPortRange $port
# Update the NSG.
$nsg | Set-AzNetworkSecurityGroup
kavyaS
  • 8,026
  • 1
  • 7
  • 19
Venkat V
  • 2,197
  • 1
  • 1
  • 10