azureazure-powershellnetwork-security-groups

Getting list of NSG and corresponding Subnet or NIC


Thanks in advance.

I'm working on Azure PowerShell Script which will get all the NSG and finds whether it is attached to NIC or Subnet and give the name of the same in CSV.

I'm stuck in parsing the NSG as it has property SubnetsText which outputs the data in below format. I'm trying to parse it using substring method but it did not work. Anybody tried this before?

[
  {
    "TapConfigurations": [],
    "HostedWorkloads": [],
    "Id": "/subscriptions/xxxx-xxxx-xxx-xxx-xxxxxx/resourceGroups/vm-test-group/providers/Microsoft.Network/networkInterfaces/testvm1VMNic"
  }
]

Below is the cmdlet

$nsg = Get-AzureRmNetworkSecurityGroup -Name  testvm1NSG -ResourceGroupName vm-test-group

$nsg.SubnetsText.ToString().Substring(lastindexof('/')+1)

Solution

  • you could just do this:

    $nsg.Subnets.Id.Split('/')[-1]
    

    this would split the string on / and get the last item from that operation, which would be the NIC name.