I am new to PS.... trying to get NSGs in a given subscription (and once this works to do this for all subscriptions) to show the following properties (NSG Name, Location, Resource Group, Subnet, NIC).
I am using the below script from Getting list of NSG and corresponding Subnet or NIC but it lists same information for each NSG multiple times equal to the number of NSGs in the subscription so it has to be something wrong in the script
$azNsgs = Get-AzNetworkSecurityGroup
foreach ( $azNsg in $azNsgs ) {
if ($azNsg.Subnets.Id -ne $null) {
$NsgSubnets = $azNsg.Subnets.Id.Split('/')[-1]
}
Get-AzNetworkSecurityGroup | `
Select-Object `
@{name = 'NSG Name'; expression = {$azNsg.Name} }, `
@{name = 'Location'; expression = {$azNsg.Location} }, `
@{name = 'Resource Group Name'; expression = {$azNsg.ResourceGroupName} }, `
@{name = 'Subnets'; expression = $NsgSubnets }
}
Also would like the script to ignore null values for NIC/Subnet as some NSGs would be assigned to Subnets whilst others to NICs Finally an NSG could be assigned to multiple subnets/NICs so how do I get the $azNsg.Subnets.Id.Split('/')[-1] part working for multiple entries in Subnets.Id or NetworkInterfaces.Id and not just the last one ?
Thanks
Get-AzNetworkSecurityGroup
the second time inside of yourforeach
loop. Just use$azNsg | Select-Object ....
. – AdminOfThings[-1]
gets the last element of an array. If you don't want only the last element, then you should remove that index. Since you are using anif
statement to set$NsgSubnets
, it is not reset for when there are no subnets. The first line of yourforeach
needs to be something like$NsgSubnets = $null
. – AdminOfThings$NsgSubnets = $azNsg.Subnets.foreach({$_.Id.Split('/')[-1]})
– AdminOfThings