Export all NSG Rules in a subscription to one CSV file

Vishu 1,576 Reputation points
2025-05-04T08:33:02.1033333+00:00

Please provide a PowerShell script to export all Azure NSG's along with rules in one subscription to one csv file

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} vote

Answer accepted by question author
  1. Davi Mendes 75 Reputation points
    2025-11-03T14:55:18.52+00:00

    Autenticar no Azure

    Connect-AzAccount

    Obter todas as assinaturas

    $subscriptions = Get-AzSubscription

    Inicializar lista de regras

    $allRules = @()

    Iterar por cada assinatura

    foreach ($sub in $subscriptions) {

    Select-AzSubscription -SubscriptionId $sub.Id
    
    # Obter todos os NSGs
    
    $nsgs = Get-AzNetworkSecurityGroup
    
    foreach ($nsg in $nsgs) {
    
        foreach ($rule in $nsg.SecurityRules) {
    
            $allRules += [PSCustomObject]@{
    
                SubscriptionName   = $sub.Name
    
                ResourceGroupName  = $nsg.ResourceGroupName
    
                NSGName            = $nsg.Name
    
                RuleName           = $rule.Name
    
                Priority           = $rule.Priority
    
                Direction          = $rule.Direction
    
                Access             = $rule.Access
    
                Protocol           = $rule.Protocol
    
                SourceAddress      = ($rule.SourceAddressPrefix -join ',')
    
                DestinationAddress = ($rule.DestinationAddressPrefix -join ',')
    
                SourcePort         = ($rule.SourcePortRange -join ',')
    
                DestinationPort    = ($rule.DestinationPortRange -join ',')
    
            }
    
        }
    
    }
    

    }

    Exportar para CSV

    $allRules | Export-Csv -Path "C:\NSG_Rules.csv" -NoTypeInformation -Encoding UTF8

    0 comments No comments

0 additional answers

Sort by: Most helpful

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.