I am trying to create an PowerShell script to list Azure Network Security Groups and it's rule from all subscription and export it to CSV.
Below is my code which list all the NSG Rule Name,Description,Priority,SourceAddressPrefix,SourcePortRange,DestinationAddressPrefix,DestinationPortRange,Protocol,Access and Direction.
############# List All Azure Network Security Groups #############
$subs = Get-AzSubscription
foreach ($sub in $subs) {
Select-AzSubscription -SubscriptionId $sub.Id
$nsgs = Get-AzNetworkSecurityGroup
Foreach ($nsg in $nsgs) {
$nsgRules = $nsg.SecurityRules
foreach ($nsgRule in $nsgRules) {
$nsgRule | Select-Object @{n='SubscriptionName';e={$sub.Name}},
@{n='ResourceGroupName';e={$nsg.ResourceGroupName}},
@{n='NetworkSecurityGroupName';e={$nsg.Name}},
Name,Description,Priority,
@{Name='SourceAddressPrefix';Expression={[string]::join(",", ($_.SourceAddressPrefix))}},
@{Name='SourcePortRange';Expression={[string]::join(",", ($_.SourcePortRange))}},
@{Name='DestinationAddressPrefix';Expression={[string]::join(",", ($_.DestinationAddressPrefix))}},
@{Name='DestinationPortRange';Expression={[string]::join(",", ($_.DestinationPortRange))}},
Protocol,Access,Direction |
Export-Csv "C:\Users\admin-vishal.singh\Desktop\Test\nsg\NsgRules.csv" -NoTypeInformation -Encoding ASCII -Append
}
}
}
The output I am Getting for above script
I also tried to call object Resourcegroup, SubscriptionName under $nsgRule | Select-Object it gave me blank column with header Resourcegroup, subscriptionName.
I am trying to get output like this:
I don't know at which for loop I need to do changes to get output like above.
Basically, I am trying to list all the Azure NSGs with Rules from all subscription with there respective ResourcegroupName, subscriptionName.