I'm currently working on a script that gives me the output of every Subnet in an Azure Subscription, with links to the VNet, NSG, and the Route Table. The Route Table Name is currently missing in the script, but I want to focus on fixing the NSG right now. This is what my Script looks like:
$VNets = Get-AzVirtualNetwork
$NSG = Get-AzNetworkSecurityGroup
$VNets | ForEach-Object {
$VNettemp = $_
$result = $_.Subnets | Select-Object @{Label="Subnet Name";Expression={$_.Name}},@{Label="Subnet";Expression={$_.AddressPrefix}}
$_ | ForEach-Object {
$result | Add-Member -Name "VNet Name" -Value $_.Name -MemberType NoteProperty
}
if ($_.Subnets.NetworksecurityGroup -ne "null"){
$NSG | ForEach-Object{
if ($VNettemp.Subnets.Id -contains $_.Subnets.Id ){
$result | Add-Member -Name "NSG Name" -Value $_.name -MemberType NoteProperty -Force
}
}
}
return $result
}
The output looks like this:
Subnet Name Subnet VNet Name NSG Name
----------- ------ --------- --------
default-subnet 10.10.10.0/28 vnet-ine-test test-nsg
vnet-ine-test-snet-test 10.10.0.0/24 vnet-ine-test test-nsg
default 10.0.0.0/24 vnet-chn-docker vnet-chn-docker-nsg
vnet-test-subnet 10.0.1.0/24 vnet-chn-docker vnet-chn-docker-nsg
The desired output would look like this because 'default-subnet' and 'vnet-test-subnet' have no NSG attached:
Subnet Name Subnet VNet Name NSG Name
----------- ------ --------- --------
default-subnet 10.10.10.0/28 vnet-ine-test
vnet-ine-test-snet-test 10.10.0.0/24 vnet-ine-test test-nsg
default 10.0.0.0/24 vnet-chn-docker vnet-chn-docker-nsg
vnet-test-subnet 10.0.1.0/24 vnet-chn-docker
Does anybody know how to fix the output? I tried it with an else statement that fills in an empty value for "NSG Name" but then the name gets canceled entirely for the whole VNet. Thanks for the Help!