Share via

Powershell command. If something exists then change to something else

Jeff Fazio 36 Reputation points
2023-09-01T20:12:51.1833333+00:00

I have a powershell script that I use in Azure so that I can update multiple NSG's at the same time. Something I run into on occasion is the priority in my script is already being used on the NSG. I am wondering if there is a way to do this so that if the priority is already being used then change it to something else.

Basically it would be if -Priority 200 is already configured then use -Priority 210

Thanks

Here's an example of my script

$RGname="RG-Name"
$port= "*"
$rulename="Rule-Name"
$nsgname="NSGName-nsg"

# Get the NSG resource
$nsg = Get-AzNetworkSecurityGroup -Name $nsgname -ResourceGroupName $RGname

# Add the inbound security rule.
$nsg | Add-AzNetworkSecurityRuleConfig -Name $rulename -Description "Rule-Description" -Access Deny `
    -Protocol * -Direction Outbound -Priority 200 -SourceAddressPrefix * -SourcePortRange * `
    -DestinationAddressPrefix "1.2.3.4" -DestinationPortRange $port

# Update the NSG.
$nsg | Set-AzNetworkSecurityGroup
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

1 answer

Sort by: Most helpful
  1. Tushar Kumar 3,396 Reputation points MVP
    2023-09-01T20:30:51.39+00:00

    Hi Jeff

    Thanks for asking you questions!

    You can achieve by fetching the priorities first and check-in if the priority exists.

    
    $resourceGroup = "yourResourceGroup"
    $nsgName = "yourNsgName"
    $newRuleName = "newRuleName"
    $newPriority = 200
    
    $nsg = Get-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Name $nsgName
    
    # Get the priorities of existing rules
    $priorities = $nsg.SecurityRules | ForEach-Object { $_.Priority }
    
    # Check if the priority is already used
    if ($priorities -contains $newPriority) {
        Write-Host "Priority $newPriority is already in use. Finding the next available priority."
        # Find the next available priority
        $newPriority = $newPriority + 10
        while ($priorities -contains $newPriority) {
            $newPriority = $newPriority + 10
        }
        Write-Host "New priority set to $newPriority."
    }
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.