Add Network Security Rules to Azure NSGs w/PowerShell

Summary: This script will add specific Network Security Group Rules to Azure Network Security Groups in an Azure Subscription. This script requires a CSV input file with the following format:

NSG Name,Rule Name,Priority,Action,Protocol,Direction,Source IP,Source Port,Destination IP,Destination Port

Note: This script does not overwrite existing Rules and will skip an NSG if that rule name or priority is already set within an NSG. In addition, this script does not check to see if any preceding rules will block the new rule.

Set-NSGs.csv (example):


Set-NSGs.ps1 (example):

    Sets NSG Rules for Network Security Groups
    PS >> .\Set-NSGs.ps1
    AUTHORS: Otto Helweg
    LASTEDIT: February 9, 2021
    VERSION: 1.0.0
    POWERSHELL: Requires version 6
    Update Execution Policy and Modules:
        Set-ExecutionPolicy Bypass -Force
    Login to Azure first:
            Login-AzAccount -Subscription "<Azure Subscription>"
            Select-AzSubscription -Subscription "<Azure Subscription>"
        .\Set-NSGs.ps1 -Wait -inputFile "Set-NSGs.csv"


if (!($inputFile)) {
    $inputFile = "Set-NSGs.csv"

$csvContent = Get-Content "./$inputFile"
foreach ($item in $csvContent) {
    $duplicateRule = $false
    $nsgName,$ruleName,$priority,$access,$protocol,$direction,$sourcePrefix,$sourcePort,$destinationPrefix,$destinationPort = $item.Split(",")

    Write-Output "Working on Rule: $nsgName - $ruleName"
    $nsg = Get-AzNetworkSecurityGroup -Name $nsgName

    foreach ($rule in $nsg.SecurityRules) {
        if (($rule.Name -eq $ruleName) -or (($rule.Direction -eq $direction) -and ($rule.Priority -eq $priority))) {
            Write-Output ">> Duplicate Rule Found! Check $ruleName, $direction and $priority"
            $duplicateRule = $true

    if ($duplicateRule -eq $false) {
        Write-Output "> Creating new NSG Rule"

        # Add the inbound security rule.
        $nsg | Add-AzNetworkSecurityRuleConfig -Name $ruleName -Description "Added by PowerShell" -Access $access `
            -Protocol $protocol -Direction $direction -Priority $priority -SourceAddressPrefix $sourcePrefix -SourcePortRange $sourcePort `
            -DestinationAddressPrefix $destinationPrefix -DestinationPortRange $destinationPort

        # Update the NSG.
        $nsg | Set-AzNetworkSecurityGroup